js check for most frequent value in array 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), {});

// Examples
countOccurrences([2, 1, 3, 3, 2, 3]);               // { '1': 1, '2': 2, '3': 3 }
countOccurrences(['a', 'b', 'a', 'c', 'a', 'b']);   // { 'a': 3, 'b': 2, 'c': 1 }

Example 2: js check for most frequent value in array

//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 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();}

Tags:

Misc Example