Check if an Array contains Duplicates in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

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 size of the Set to the array's length.
  3. If the Set contains as many values as the array, then the array doesn't contain 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 duplicates from the array.

The Set object stores only unique values and removes all duplicates automatically.

When an array containing duplicates is passed to the Set object, all duplicates get removed.

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, then the array doesn't contain any duplicates.

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

Check if an Array contains Duplicates with some() #

To check if an array contains duplicates:

  1. Use the Array.some() method to iterate over the array.
  2. 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 Array.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 returning true.

Our if statement checks 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, the value is contained at least twice in the array.

If the condition is met at least once, the some() method short-circuits returning true.

This is good for performance because we don't need to needlessly loop after we have the solution.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.