find mode js
//Everyone was sharing complex answers. I'm just gonna put my simple-ish code here
//It suuports multiple values of same frequency
//If u want the first value and not multiple in case of multiple modes just add [0] after pop() function
function checkMostFrequent(arr) {
var outArr = []; //output variable (an array containing arrays)
for (let i = 0; i < arr.length; i++) {
var pushed = false; //keep track
for (let j = 0; j < outArr.length; j++) {
if (!outArr[j].includes(arr[i])) { //for arrays include function checks for given elements
outArr[j].push(arr[i]); //push if array doesn't have the variable
pushed = true;
break;
}
}
if (!pushed) {
outArr.push([arr[i]]); //push a brand new array of array
}
}
return outArr.pop(); //return the last one (therefore most frequent) //for this case pop() is similar to outArr[outArr.length-1]
}
//The code can be modifed without much difficulty to return the index or just make frequency checks too
Here is the tiny oneLiner version if you want to put it in minified stuff:
checkMostFrequent=a=>{var o=[],p;a.map(i=>{p=0;o.map(j=>{if(!j.includes(i)&&!p){j.push(i);p=1}});if(!p){o.push([i])}});return o.pop()} //replace "var o=[],p" with "o=[]" to save 6 bytes at the cost of not being able to use "o" or "p" as a global variable