Check if array has duplicate elements
11 March 2022 (Updated 25 April 2022)
On this page
TLDR
You want a function that takes an array and checks if it contains any duplicate elements:
hasDuplicates([2, 4, 4, 6]) // true
hasDuplicates([2, 4, 6]) // false
Here’s how in JavaScript:
const hasDuplicates = arr => {
return new Set(arr).size !== arr.length
}
Explanation
This works by first converting the given array to a Set
– a data structure containing only unique values. We then check whether the number of unique elements in the set is equal to the total number of elements in the array.
If they aren’t equal, then the array must have at least one duplicate because when converting it to a set, we lost some elements (the set removes any duplicate elements).
Tagged:
Algorithms