Count Occurrences of each Element in Array in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Count Occurrences of each Element in Array #

To count the occurrences of each element in an array:

  1. Declare a variable that stores an empty object.
  2. Use the for...of loop to iterate over the array.
  3. On each iteration, increment the count for the current element if it exists or initialize the count to 1.
index.js
const arr = ['a', 'b', 'a', 'a', 'c', 'c']; const count = {}; for (const element of arr) { if (count[element]) { count[element] += 1; } else { count[element] = 1; } } console.log(count); // 👉️ {a: 3, b: 1, c: 2}

We first declare a variable and set it to an empty object.

The for...of loop allows us to iterate over the array.

Our if condition checks if the current array element is present as a key in the object.

If the element is present in the object, we increment the corresponding value, otherwise we initialize the key to 1.

The keys in the object are the array elements, and the values are the occurrences of each element in the array.

This approach also works if your array consists of numbers.
index.js
const arr = [1, 1, 1, 2, 3, 3]; const count = {}; for (const element of arr) { if (count[element]) { count[element] += 1; } else { count[element] = 1; } } console.log(count); // 👉️ {1: 3, 2: 1, 3: 2}

This seems a bit confusing as object keys can only be of type string or symbol in JavaScript.

However, you can still access the object's keys either way.

index.js
console.log(count[1]); // 👉️ 3 console.log(count['1']); // 👉️ 3
If you try to access the key of the object using a number, it will automatically get converted to a string under the hood.

You can achieve the same result by using a basic for loop.

index.js
const arr = ['a', 'b', 'a', 'a', 'c', 'c']; const count = {}; for (let index = 0; index < arr.length; index++) { const element = arr[index]; if (count[element]) { count[element] += 1; } else { count[element] = 1; } } console.log(count); // 👉️ {a: 3, b: 1, c: 2}

This code snippet achieves the same goal. However, we use a basic for loop, instead of the for...of loop.

Which approach you pick is a matter of personal preference. I'd pick the for...of loop in all cases where I need access to the index.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.