Check if an Array contains Duplicates in JavaScript

avatar

Borislav Hadzhiev

Sat Oct 16 20212 min read

Check if an Array contains Duplicates #

To check if an array contains duplicates:

  1. Pass the array to the Set constructor and access the size property on the Set.
  2. Compare the Set's size property to the array's length. Sets only contain unique values, so any duplicates get automatically removed.
  3. If the Set contains as many values as the array does, then the array doesn't contain any duplicates.
index.js
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.

index.js
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.

Check if an Array contains Duplicates with some() #

An alternative approach is to use the Array.some method.

To check if an array contains duplicates:

  1. Call the some method on the array passing it a function.
  2. On each iteration, check if the index of the first occurrence of the current value is NOT equal to the index of its last occurrence.
  3. If the condition is met, then the array contains duplicates.
index.js
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.

In our 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.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee