I\'m looking for an elegant way of determining which element has the highest occurrence (mode) in a JavaScript array.
For example, in
[\'pear\', \'a
This function is generic function for every type of info. It counts the occurrence of the elements and then returns array with maximum occurring elements.
function mode () {
var arr = [].slice.call(arguments);
if ((args.length == 1) && (typeof args[0] === "object")) {
args = args[0].mode();
}
var obj = {};
for(var i = 0; i < arr.length; i++) {
if(obj[arr[i]] === undefined) obj[arr[i]] = 1;
else obj[arr[i]]++;
}
var max = 0;
for (w in obj) {
if (obj[w] > max) max = obj[w];
}
ret_val = [];
for (w in obj) {
if (obj[w] == max) ret_val.push(w);
}
return ret_val;
}