Knowing how to check for duplicates in an array can be useful in many different situations. Here are two ways to accomplish this:
- Combination of some() and indexOf()
- Set()
Some Plus IndexOf
The some() method can be used to check if each element in an array passes a function.
We'll be passing a callback with two arguments: the element of the array and the index of the element.
In order to check whether a value already exists in an array (a duplicate), we'll use the indexOf() method and pass in each value from our colors array.
The indexOf() method will return the index of the first occurence of the value.
Remember how our callback in the some() method also contains the index (i)?
This will be our verification!
If this condition passes and there are equal index values, that means there are duplicates.
In our example, we have two values of "blue" and two values of "red".
This will satisfy our index comparison, and return true.
const colorsArray = ['red', 'blue', 'green', 'blue', 'red']
const doesArrayHaveDuplicates = colorsArray.some(
(val, i) => colorsArray.indexOf(val) !== i
)
console.log(doesArrayHaveDuplicates) // true
Set
Set is one of the great features that came with ES6.
You can think of Set as an object with a collection of values.
The only catch is that each value in the Set must be unique, which makes it perfect for finding duplicates!
If a value already exists in the Set, it won't be added to the collection.
In our example, we create a new Set object with our colors array as our collection of values.
Set internally will check for unique values, and since there are two values of "red", the size of our Set will only by 3 (instead of 4).
The length of our colors array is 4, so our validation will return true, meaning duplicates exist.
const doesArrayHaveDuplicates = array => {
return array.length !== new Set(array).size
}
const colorsArray = ['red', 'blue', 'green', 'red']
console.log(doesArrayHaveDuplicates(colorsArray)) // fal