Count Occurrences of each Element in Array in JavaScript

avatar

Borislav Hadzhiev

Fri Oct 15 20213 min read

banner

Photo by Joshua Sazon

Count Occurrences of each Element in Array #

To count the occurrences of each element in an array:

  1. Create an object that will store each array element as the key and its number of occurrences as the value.
  2. Use the for...of loop to iterate over the array.
  3. On each iteration, increment the count for the specific element if it exists in the object or set the count of the element to 1 if it doesn't.
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 we already encountered a specific array element and initialized it on the object or not.

If it's the first time we encounter an array element, we set the element as the object's key and initialize its value to 1.

If we encounter the same element again, we increment the value of the corresponding key in the object.

The final result is an object, whose keys are the array elements and the values - their occurrences 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.

The for...of loop is not supported in Internet Explorer. If you have to support the browser use a basic for loop instead.
index.js
// Supported in IE 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.

It's a bit more cluttered and indirect, however most developers are used to reading for loops and it gets the job done if you have to support Internet Explorer.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee