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.tsx304 chars9 lines
Explanation:
We first define a function mode
that takes an array arr
as its parameter.
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
.
We then find the maximum frequency by using the Math.max()
function on the array of frequency counts.
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.
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.tsx77 chars3 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