How to Find an Item in Array Which Has the Most Occurrences

Get the element with the highest occurrence in an array

This is just the mode. Here's a quick, non-optimized solution. It should be O(n).

function mode(array)
{
if(array.length == 0)
return null;
var modeMap = {};
var maxEl = array[0], maxCount = 1;
for(var i = 0; i < array.length; i++)
{
var el = array[i];
if(modeMap[el] == null)
modeMap[el] = 1;
else
modeMap[el]++;
if(modeMap[el] > maxCount)
{
maxEl = el;
maxCount = modeMap[el];
}
}
return maxEl;
}

Get the item that appears the most times in an array

I would do something like:

var store = ['1','2','2','3','4'];
var frequency = {}; // array of frequency.
var max = 0; // holds the max frequency.
var result; // holds the max frequency element.
for(var v in store) {
frequency[store[v]]=(frequency[store[v]] || 0)+1; // increment frequency.
if(frequency[store[v]] > max) { // is this frequency > max so far ?
max = frequency[store[v]]; // update max.
result = store[v]; // update result.
}
}

get most occurring elements in array JavaScript

You can count the items with reduce and find the maximum occurring count. Then you can filter any keys that have that count:

let arr = ['foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'baz', 'baz'];
let counts = arr.reduce((a, c) => { a[c] = (a[c] || 0) + 1; return a;}, {});let maxCount = Math.max(...Object.values(counts));let mostFrequent = Object.keys(counts).filter(k => counts[k] === maxCount);
console.log(mostFrequent);

How to find an item in array which has the most occurrences

First build a hash mapping each value in the array to its frequency…

arr = [1, 1, 1, 2, 3]

freq = arr.inject(Hash.new(0)) { |h,v| h[v] += 1; h }
#=> {1=>3, 2=>1, 3=>1}

… then use the frequency table to find the element with the highest frequency:

arr.max_by { |v| freq[v] }
#=> 1

Highest occurrence in an array or first selected

You could use something like this:

function mostFrequent(array) {
var map = array.map(function(a) {
return array.filter(function(b) {
return a === b;
}).length;
});

return array[map.indexOf(Math.max.apply(null, map))];
}

First it creates a map of occurrences of all the values. Next just check with Math.max which one is the highest. Check the indexOf for the first value that has that highest occurences and return the value of that index in the original array.

ES2015

If ES2015 is an option, you could use this one. It's less code.

function mostFrequent(array) {
let map = array.map((a) => array.filter((b) => a === b).length);

return array[map.indexOf(Math.max.apply(null, map))];
}

And if you're in a place where even the spread operator is allowed (NodeJS v5 and up, Chrome 54) you could replace Math.max.apply(null, map) for Math.max(...map)!

Counting the occurrences / frequency of array elements