find the mode of a list of numbers in javascript

To find the mode of a list of numbers in Javascript, one approach is to create a frequency table using an object and a loop, which counts the number of occurrences of each value in the array. Then, we can loop through the frequency table to find the value with the highest frequency (i.e., the mode).

Here's an example code snippet that implements this approach:

index.tsx
function findMode(arr) {
  // create frequency table
  const freqs = {};
  for (const num of arr) {
    freqs[num] = (freqs[num] || 0) + 1;
  }

  // find value with highest frequency
  let maxFreq = 0;
  let mode = null;
  for (const [value, freq] of Object.entries(freqs)) {
    if (freq > maxFreq) {
      maxFreq = freq;
      mode = parseInt(value); // convert string to number
    }
  }

  return mode;
}

const numbers = [1, 2, 2, 3, 3, 3, 4, 4, 5];
const mode = findMode(numbers);
console.log(mode); // output: 3
521 chars
24 lines

In this example, we define a function findMode which takes an array arr as input. The function first creates an empty object freqs to store the frequency table. Then, we loop through each value num in the array, and increment its count in the frequency table using freqs[num] = (freqs[num] || 0) + 1. This uses the || operator and a default value of 0 to handle cases where the value hasn't been seen before.

After creating the frequency table, we define two variables maxFreq and mode to hold the maximum frequency and corresponding value. We then loop through each entry in the frequency table using Object.entries(freqs), which returns an array of key-value pairs. For each entry, we check if its frequency is higher than the current maximum maxFreq. If it is, we update maxFreq and mode to the current value. Finally, we return the mode as a number.

We test the function with an example array of numbers numbers, and log the result to the console using console.log. The output should be 3, which is the mode of the array.

gistlibby LogSnag