When working with arrays in JavaScript, sometimes we need to count the unique elements in an array in JavaScript. This article will show you how to do it using two methods: a Set
object and a Reduce()
method. Follow the explanations and examples below to achieve your goal.
Count the Unique Elements in an Array in JavaScript
Using Set object
The Set
object in JavaScript is an object type used to create a unique collection of values passed. The Set
object allows us to store data types from simple to complex in a unique and non-duplicating.
To count the unique elements in an Array in JavaScript using the Set
object, we initialize a new set to store the array passed. Then we use the Set.size
property to get the number of elements of that Set
object.
For example:
Let’s count the unique elements in the array below.
const arrNames = ["James", "Robert", "John", "Robert", "John"]; // Initialize new Set const names = new Set(arrNames); console.log("The number of unique elements is: " + names.size);
Output:
The number of unique elements is: 3
The number of elements that the Set.size
property returns are the number of unique elements in the array we are looking for.
Using reduce() method
The reduce()
method in JavaScript is used to iterate through each element in the array, then return a final value depending on the program of the function that we pass in.
To count the unique elements in an array in JavaScript using the reduce()
method, first, we use the reduce()
method to iterate through each element of the array. In each iteration, we use the indexOf()
function to check the element in the array and return the first element found. After each time we find the first element, we increment the counter by 1.
For example:
Let’s count the unique elements in the array below.
const arrNames = ["James", "Robert", "John", "Robert", "John"]; // Count the unique elements in the array const countName = arrNames.reduce((acc, currValue, currIndex, array) => { if (array.indexOf(currValue) === currIndex) { return acc += 1; }; return acc; }, 0); console.log("The number of unique elements is: " + countName);
Output:
The number of unique elements is: 3
The last counter value after we iterate through the array is the number of unique elements in the array that we need to find.
Summary
This article taught you how to count the unique elements in an array in JavaScript by two methods. Using a Set
object is the easiest and speediest way to get the number of unique elements, and you can apply this method in your project to achieve your goal quickly. See you in the next articles.

Hi, I’m Mary Ralston. I have experience programming in HTML, javascript, C++,… and I want to share with you my experience. So if you want to know more about the above languages read my articles