Count the Unique Elements in an Array in JavaScript

avatar

Borislav Hadzhiev

Fri Oct 15 20212 min read

banner

Photo by Seth Doyle

Count the Unique Elements in an Array in JavaScript #

To count the unique elements in an array, pass the array to the Set constructor and access the size property on the set. The Set object only stores unique values and automatically removes duplicates. The size property returns the number of values in the Set.

index.js
const arr = ['a', 'b', 'a', 'c', 'b']; const uniqueCount = new Set(arr).size; console.log(uniqueCount); // 👉️ 3

The Set object only stores unique values. Even if the supplied array contains duplicates, they don't get added to the Set.

The last step is to access the size property of the set. The property returns the number of values the Set contains.

An alternative approach is to loop over the elements in the array.

index.js
const arr = ['a', 'b', 'a', 'c', 'b']; let uniqueCount = 0; arr.forEach((element, index) => { if (arr.indexOf(element) === index) { uniqueCount += 1; } });

This code snippet also counts the unique elements in the array, however this time we use the Array.forEach method.

The function we passed to the forEach method gets called with each element in the array.

In our if statement, we use the Array.indexOf to determine if this is the first occurrence of the element in the array.

The indexOf method returns the index of the first occurrence of a value in an array.

We know that if the current index in the loop is equal to the index of the first occurrence of an element, we haven't encountered this element in any of the previous iterations.

If this is the first time we encounter an element, we increment the value of the uniqueCount by 1.

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