avatarJohn Au-Yeung

Summarize

How to Get the Element with the Highest Number of Occurrences in a JavaScript Array?

Photo by Tony Hand on Unsplash

Sometimes, we want to get the element with the highest number of occurrences in a JavaScript array.

In this article, we'll look at how to get the element with the highest number of occurrences in a JavaScript array.

Get the Element with the Highest Number of Occurrences in a JavaScript Array

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.

Conclusion

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.

In Plain English 🚀

Thank you for being a part of the In Plain English community! Before you go:

Programming
Web Development
Technology
Software Development
JavaScript
Recommended from ReadMedium