I have written a relatively convoluted implementation of Microsoft Excel’s MODE.MULT function, which returns an array of the most frequently occurring, or repetitive values in an array. It’s implemented with three loops, including one nested into another, and I’m suspecting that there is a simpler way to go about it. For information, it’s using _.uniq from Lo-Dash for extracting duplicate values out of the returned array.
function MODEMULT(range) {
var n = range.length;
var max = 0;
var counts = new Array();
var result = new Array();
for (var i = 0; i < n; i++) {
counts[i] = 0;
for (var j = 0; j < n; j++) {
if (range[j] === range [i]) {
counts[i]++;
max = (counts[i] > max) ? counts[i] : max;
}
}
}
for (var k = 0; k < n; k++) {
if (counts[k] === max) {
result.push(range[k]);
}
}
return _.uniq(result);
}
For testing purposes, MODEMULT([1,2,3,4,3,2,1,2,3]) should return [2,3]
Thanks in advance for your help!
You could go with less loops, although there is an impact on memory usage as you will keep counts on all unique entries in the original range: