Sometimes, we want to check if a JavaScript array contains duplicate values.
In this article, we’ll look at how to check if a JavaScript array contains duplicate values.
Check if a JavaScript Array Contains Duplicate Values
To check if a JavaScript array contains duplicate values, we can use the JavaScript array some
and indexOf
methods.
For instance, we write:
const arr = [11, 22, 11, 22];
const hasDuplicate = arr.some((val, i) => arr.indexOf(val) !== i);
console.log(hasDuplicate)
to check if arr
has duplicate values.
We call some
with a callback to check if some array entries matches the condition returned by the callback.
indexOf
returns the index of the first element that matches a given value.
So if indexOf
returns a value that isn’t equal to the index i
, we know that the value is a duplicate.
Therefore, the console log should log true
.
Conclusion
To check if a JavaScript array contains duplicate values, we can use the JavaScript array some
and indexOf
methods.