Borislav Hadzhiev
Sat Oct 16 2021·2 min read
Photo by Christian Bowen
To check if an array contains duplicates:
Set
constructor and access the size
property on the
Set
.Set
's size
property to the array's length. Sets only contain
unique values, so any duplicates get automatically removed.Set
contains as many values as the array does, then the array
doesn't contain any duplicates.const arr1 = ['a', 'a']; const arr2 = ['a', 'b']; function containsDuplicates(array) { if (array.length !== new Set(array).size) { return true; } return false; } console.log(containsDuplicates(arr1)); // 👉️ true console.log(containsDuplicates(arr2)); // 👉️ false
We used the Set object to remove all the duplicates from the array.
The Set
object allows us to store unique values and removes all duplicates
automatically.
If we pass it an array containing the same value multiple times, it would only
get added once to the Set
.
console.log(new Set(['a', 'a', 'a'])); // 👉️ { 'a' }
The size
property on the Set
returns the number of values the Set
contains.
If the Set
object contains as many values as the array, we know that the array
doesn't have duplicates.
An alternative approach is to use the Array.some method.
To check if an array contains duplicates:
some
method on the array passing it a function.const arr1 = ['a', 'a']; const arr2 = ['a', 'b']; function containsDuplicates(array) { const result = array.some(element => { if (array.indexOf(element) !== array.lastIndexOf(element)) { return true; } return false; }); return result; } console.log(containsDuplicates(arr1)); // 👉️ true console.log(containsDuplicates(arr2)); // 👉️ false
The function we passed to the some
method gets called with each element in the
array, until it returns a truthy value or iterates over the entire array.
If the function returns true
at least once, the some
method short-circuits
and returns true
.
if
statement, we check if the index of the first occurrence of an element is NOT equal to the index of the last occurrence of the same element.If the first and last indexes of an element in an array are different, we know that the value is contained at least twice in the array.
If the condition is met at least once, we return true
and short-circuit the
some
method.
This is good for performance because we don't need to needlessly loop after we've got the result.