How to check if an array contains duplicate values in JavaScript?
Checking if a JavaScript Array contains duplicate values is something that might come in handy. For instance, I frequently use this in tests to perform verifications.
Let's now see how to do it. Considering the following 2 arrays:
const array1 = ['one', 'two', 'three'];
const array2 = ['one', 'two', 'two', 'three'];
The first one, array1
, contains no duplicates.
However, the second, array2
, contains the item two
twice.
In an ES2015/ES6 compatible environment, which is very likely if you are using any modern browser or supported Node.js version, checking for duplicates is as easy as running the following snippet:
function containsDuplicates(array) {
return array.length !== new Set(array).size;
}