Categories
JavaScript Answers

How to count the occurrences / frequency of array elements with JavaScript?

Spread the love

To count the occurrences / frequency of array elements with JavaScript, we use a for-of loop.

For instance, we write

const arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
const counts = {};

for (const num of arr) {
  counts[num] = counts[num] ? counts[num] + 1 : 1;
}

to define the counts object.

Then we use a for-of loop to loop through the arr array and set counts[num] to counts[num] + 1 if it’s already set and 1 otherwise.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published.