find the mode of all elements in an array in javascript

To find the mode of all elements in an array in JavaScript, we can use a combination of the reduce() and filter() functions.

Here's the code:

index.tsx
function mode(arr) {
  const freqCounter = arr.reduce((acc, val) => {
    acc[val] = (acc[val] || 0) + 1;
    return acc;
  }, {});
  const maxFrequency = Math.max(...Object.values(freqCounter));
  return Object.keys(freqCounter).filter(key => freqCounter[key] === maxFrequency).map(s => parseInt(s));
}
304 chars
9 lines

Explanation:

  1. We first define a function mode that takes an array arr as its parameter.

  2. We then use the reduce() function to create an object that stores the frequency of each unique element in the array. The initial value of the accumulator (the acc variable) is an empty object, and the callback function for reduce() increments the count for each element encountered in arr.

  3. We then find the maximum frequency by using the Math.max() function on the array of frequency counts.

  4. We use Object.keys() to get an array of all the keys (unique values) in our frequency object, and filter them down to only include the ones with the maximum frequency.

  5. Finally, we use .map() to cast our keys back into integers (since they were converted to strings when we used them as object keys).

Here's an example of using this function:

index.tsx
const arr = [1, 2, 3, 4, 4, 5, 5, 5];
console.log(mode(arr)); // Output: [5]
77 chars
3 lines

In this case, the mode of the array [1, 2, 3, 4, 4, 5, 5, 5] is 5, because it occurs more frequently than any other element.

gistlibby LogSnag