function recurrent(arr) {
var count = {},
highest = 0,
ret = null;
for (var i = 0; i < arr.length; i++) {
var curr = arr[i];
count[curr] = typeof count[curr] === "undefined" ? 1 : count[curr] + 1;
}
for (var name in count) {
if (!count.hasOwnProperty(name)) continue;
var currCount = count[name];
if (currCount > highest) {
highest = currCount;
ret = name;
}
}
return ret;
}
Usage(here you find the jsfiddle):
var a = [0, 0, 0, 1, 1, 2, 3, 4, 5, 5, 5, 5, 5, 6];
console.log(recurrent(a)); // 5
Explanation:
count[curr] = typeof count[curr] === "undefined" ? 1 : count[curr] + 1;
With this line we initialize(or increase if already set) the count of that element in the array so that we can use it later to see which element appears the most.
if (currCount > highest) {
highest = currCount;
ret = name;
}
If the count of the current element is greater than the highest counted until now, this block updates the highest value with the current one and set the return name to the current one.