To get the element with the highest number of occurrences in a JavaScript array, we can use some array methods to get the number of occurrences of each item and sort the values to get the highest value from the list.
For instance, we can write:
const mode = (arr) => {
return arr.sort((a, b) =>
arr.filter(v => v === a).length -
arr.filter(v => v === b).length
).pop();
}
console.log(mode(['pear', 'apple', 'orange', 'apple']));
to create the mode
function that takes an array.
In the function, we call sort
with a callback that takes the a
and b
entries from arr
that are being iterated through, then we return the highest number of occurrences by using the filter
method to get the number of occurrences of each item a
and b
.
We call filter
to return an array with all a
‘s and b
‘s and get the length of it.
Then we call pop
on the returned array to return the last item from the array returned by sort
, which is the item in arr
with the highest number of occurrences.
Therefore, the console log should log 'apple'
as a result.