How to find most frequent item of an array? [Updated]
Usama Tahir
263

I don’t normally comment on posts like this, but this is a terrible implementation. Do not use this code if you are trying to find the most frequent element. This is a linear problem and should not be executed in O(n²). Here is a much faster implementation using a hash map, and a greedy algorithm:

var cats = ['Tom','Fluffy','Tom','Bella','Chloe','Tom','Chloe'];
(function(array){
let result, // This is the value we will return
best = -1, // Initialize the comparison for greedy
lookup = {}; // Hashmap for essentially constant lookup
   // Loop to go through array and count elements
for(let i = 0; i < array.length; i++){
// could replace block with `x[a[i]] = (x[a[i]] + 1)|0`
//but far less readable
if (lookup[array[i]] == undefined){
lookup[array[i]] = 0;
}
lookup[array[i]]++; // Increment count
if(lookup[array[i]] > best){ // Greedy for best element
best = lookup[array[i]];
result = array[i]
}
}
   //will return most frequent item in array cats
return result;
})(cats);
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.