Categories
JavaScript Answers

How to get the element with the highest occurrence in an array with JavaScript?

Spread the love

Sometimes, we want to get the element with the highest occurrence in an array with JavaScript.

In this article, we’ll look at how to get the element with the highest occurrence in an array with JavaScript.

How to get the element with the highest occurrence in an array with JavaScript?

To get the element with the highest occurrence in an array with JavaScript, we can use some array methods.

For instance, we write

const mode = (arr) => {
  return arr
    .sort(
      (a, b) =>
        arr.filter((v) => v === a).length - arr.filter((v) => v === b).length
    )
    .pop();
};

const highest = mode(["pear", "apple", "orange", "apple"]);

to define the mode function that returns arr sorted by the most occurrences of each entry.

We call arr.sort with a callback that get the length of the array with value v equal to a and b.

We use filter to get an array with all the entries with a and b.

Then we subtract their lengths to do the sorting in ascending order.

Finally, we call pop to return the last entry after removing it.

Therefore, highest is 'apple'.

Conclusion

To get the element with the highest occurrence in an array with JavaScript, we can use some array methods.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *