How to use the reduce() method In Javascript
To find the highest count of elements we can use the “reduce” method.
Example: This example shows the use of the above-explained approach.
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
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:
Table of Content
- Method 1: Using the reduce() method
- Method 2: Using the JavaScript Map()
- Method 3: Using the Math.max method
- Method 4: Using sorting
Contact Us