Saturday, December 28, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Program to Find the Most Frequently Occurring Element in an Array

JavaScript Program to Find the Most Frequently Occurring Element in an Array

In this article, we are going to learn how to find the most frequently occurring element in an array we can use objects to count the occurrences of each element in an array.

Methods to find the most frequently occurring element in an array in JavaScript:

Method 1: Using the reduce() method

To find the highest count of elements we can use the “reduce” method.

Example: This example shows the use of the above-explained approach.

Javascript




function mostFrequentUsingReduce(arr) {
  const counts = arr.reduce((acc, num) => {
    acc[num] = (acc[num] || 0) + 1;
    return acc;
  }, {});
  
  return Object.keys(counts).reduce((a, b) => 
      (counts[a] > counts[b] ? a : b));
}
  
const array = 
    ['Cat', 'Dog', 'Cat', 'Goat', 'Cow', 'Cat', ];
console.log(mostFrequentUsingReduce(array));


Output

Cat

Method 2: Using the JavaScript Map()

By using the “Map” Data Structure we can store the occurrence of elements in an array.

Example:This example shows the use of the above-explained approach.

Javascript




function mostFrequentUsingMap(arr) {
  const counts = new Map();
  
  for (let num of arr) {
    counts.set(num, (counts.get(num) || 0) + 1);
  }
  
  let mostFrequent;
  let maxCount = 0;
  
  counts.forEach((count, num) => {
    if (count > maxCount) {
      maxCount = count;
      mostFrequent = num;
    }
  });
  
  return mostFrequent;
}
  
const array = [1, 2, 2, 3, 2, 3, 4];
console.log(mostFrequentUsingMap(array));


Output

2

Method 3: Using the Math.max method

By using “Math.max” also we can find the highest frequency of given array elements.

Example: This example shows the use of the above-explained approach.

Javascript




function mostFrequentUsingMathMax(arr) {
  const counts = {};
  
  for (let num of arr) {
    counts[num] = (counts[num] || 0) + 1;
  }
  
  const maxCount = 
      Math.max(...Object.values(counts));
  const mostFrequent = 
      Object.keys(counts).find(key => 
        counts[key] === maxCount);
  
  return mostFrequent;
}
  
const array = [1, 5, 2, 3, 5, 6, 4];
console.log(mostFrequentUsingMathMax(array));


Output

5
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments