How to use sorting In Javascript
This approach sorts the array, then iterates through it, counting consecutive occurrences of each element. It keeps track of the most frequent element encountered so far and updates it if a new element becomes more frequent. Finally, it returns the most frequent element found.
function mostFrequentUsingSorting(arr) {
arr.sort(); // Sort the array to group same elements together
let maxCount = 0;
let mostFrequent;
let currentCount = 1;
for (let i = 1; i < arr.length; i++) {
if (arr[i] === arr[i - 1]) {
currentCount++;
} else {
if (currentCount > maxCount) {
maxCount = currentCount;
mostFrequent = arr[i - 1];
}
currentCount = 1; // Reset current count
}
}
// Check for the last element
if (currentCount > maxCount) {
maxCount = currentCount;
mostFrequent = arr[arr.length - 1];
}
return mostFrequent;
}
// Example usage
const array = ['Cat', 'Dog', 'Cat', 'Goat', 'Cow', 'Cat'];
console.log(mostFrequentUsingSorting(array)); // Output: Cat
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