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. e.g. I sometimes use this in tests to perform some quick verifications.
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, it's as easy as running the following snippet:
function containsDuplicates(array) {
return array.length !== new Set(array).size;
}