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.tsx521 chars24 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