Categories
JavaScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *