How to count unique elements in array without sorting with JavaScript?

Sometimes, we want to count unique elements in array without sorting with JavaScript.

In this article, we’ll look at how to count unique elements in array without sorting with JavaScript.

How to count unique elements in array without sorting with JavaScript?

To count unique elements in array without sorting with JavaScript, we can convert the array to a set and then get its size with the size property.

For instance, we write:

const countUnique = (iterable) => {
  return new Set(iterable).size;
}

console.log(countUnique([5, 6, 5, 6]));

We create the countUniquer function that takes an iterable object.

In the function, we convert iterable to a set with the Set constructor.

And then we get the size of the set with the size property.

Therefore, the console log should log 2.

Conclusion

To count unique elements in array without sorting with JavaScript, we can convert the array to a set and then get its size with the size property.