find mode js

Solutions on MaxInterview for find mode js by the best coders in the world

showing results for - "find mode js"
Mats
23 Nov 2020
1//Everyone was sharing complex answers. I'm just gonna put my simple-ish code here
2//It suuports multiple values of same frequency
3//If u want the first value and not multiple in case of multiple modes just add [0] after pop() function
4function checkMostFrequent(arr) {
5  var outArr = []; //output variable (an array containing arrays)
6  for (let i = 0; i < arr.length; i++) { 
7    var pushed = false; //keep track
8    for (let j = 0; j < outArr.length; j++) {
9      if (!outArr[j].includes(arr[i])) { //for arrays include function checks for given elements
10        outArr[j].push(arr[i]); //push if array doesn't have the variable
11        pushed = true;
12        break;
13      }
14    }
15    if (!pushed) {
16      outArr.push([arr[i]]); //push a brand new array of array
17    }
18  }
19  return outArr.pop(); //return the last one (therefore most frequent) //for this case pop() is similar to outArr[outArr.length-1]
20}
21//The code can be modifed without much difficulty to return the index or just make frequency checks too
22
23Here is the tiny oneLiner version if you want to put it in minified stuff:
24
25checkMostFrequent=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