Categories
JavaScript Answers

How to check if an array has duplicate values with JavaScript?

Spread the love

Sometimes, we want to check if an array has duplicate values with JavaScript.

In this article, we’ll look at how to check if an array has duplicate values with JavaScript.

How to check if an array has duplicate values with JavaScript?

To check if an array has duplicate values with JavaScript, we can use sets.

For instance, we write

const hasDuplicates = (array) => {
  return new Set(array).size !== array.length;
};

to convert array to a set with the Set constructor.

Then we check that its size isn’t the same as the array‘s length to see if it has any duplicates.

If it has duplicate values, then the set created from array won’t have the same size as the original array.

Conclusion

To check if an array has duplicate values with JavaScript, we can use sets.

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 *