how to get three most frequent index values of an array into new array javascript code example
Example 1: javascript Count the frequency of a value in an array
const countOccurrences = arr => arr.reduce((prev, curr) => (prev[curr] = ++prev[curr] || 1, prev), {});
countOccurrences([2, 1, 3, 3, 2, 3]);
countOccurrences(['a', 'b', 'a', 'c', 'a', 'b']);
Example 2: js check for most frequent value in array
function checkMostFrequent(arr) {
var outArr = [];
for (let i = 0; i < arr.length; i++) {
var pushed = false;
for (let j = 0; j < outArr.length; j++) {
if (!outArr[j].includes(arr[i])) {
outArr[j].push(arr[i]);
pushed = true;
break;
}
}
if (!pushed) {
outArr.push([arr[i]]);
}
}
return outArr.pop();
}
Here is the shorthand version if you want to put it in minified stuff:
function checkMostFrequent(a){var o=[];a.forEach(i=>{var p=0;o.forEach(j=>{if(!j.includes(i)&&!p){j.push(i);p=1;}});if(!p){o.push([i]);}});return o.pop();}