How to Check if an Array Contains Duplicates in JavaScript
Validating the uniqueness of elements in an array is a common requirement in JavaScript. You might need to ensure all user IDs in a list are unique, prevent duplicate entries from being submitted, or simply check the integrity of your data.
This guide will demonstrate the most efficient and modern methods for detecting duplicates in an array of primitive values (like strings or numbers) and in an array of objects. We will cover the elegant Set object approach and contrast it with other functional methods like some().
The Core Method: Comparing Set Size to Array Length
The simplest and most readable way to check for duplicates in an array of primitive values is to use a Set. A Set is a collection of unique values, so it automatically discards any duplicates when it's created.
The logic is straightforward:
- Create a
Setfrom the array. - Compare the
sizeof theSetto thelengthof the original array. - If the sizes are different, the array contained duplicates.
For example, imagine you have two arrays, one with duplicates and one without.
// Problem: One of these has duplicates
const arrayWithDuplicates = ['a', 'b', 'c', 'a'];
const arrayWithoutDuplicates = ['a', 'b', 'c', 'd'];
This function concisely implements the Set comparison.
function hasDuplicates(array) {
return new Set(array).size !== array.length;
}
// Example Usage:
console.log(hasDuplicates(['a', 'b', 'c', 'a'])); // Output: true
console.log(hasDuplicates(['a', 'b', 'c', 'd'])); // Output: false
But, how it works? When we pass an array to new Set(), a new Set object is created containing only the unique elements.
const array = ['a', 'b', 'c', 'a'];
const uniqueElements = new Set(array);
console.log(uniqueElements); // Output: Set(3) { 'a', 'b', 'c' }
console.log(uniqueElements.size); // Output: 3
console.log(array.length); // Output: 4
Since 3 !== 4, we know the original array had duplicates.
An Alternative Method: Using some() with indexOf
While the Set method is often preferred for its readability, you can also use the Array.prototype.some() method. This approach iterates through the array and stops as soon as it finds a duplicate.
The logic:
- For each element, check if its first found index in the array is different from the current index. If it is, that element must have appeared earlier, making it a duplicate.
Solution:
function hasDuplicates(array) {
return array.some((item, index) => array.indexOf(item) !== index);
}
// Example Usage:
console.log(hasDuplicates(['a', 'b', 'c', 'a'])); // Output: true
console.log(hasDuplicates(['a', 'b', 'c', 'd'])); // Output: false
The some() method will stop iterating and return true as soon as the callback function returns true, which makes this method efficient.
Checking for Duplicates in an Array of Objects
The methods above don't work directly on objects because objects are compared by reference, not by value. Two different objects with the same properties are not considered equal.
// Problem: How to find duplicates based on the 'id' property?
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' },
{ id: 1, name: 'Alicia' } // Duplicate ID
];
To solve this, we must first extract the property we want to check for uniqueness.
Using map() with a Set
This method is an extension of our first approach. We first create an array of just the values we care about (the IDs) and then use a Set to check for duplicates.
Solution:
function hasDuplicateIds(array) {
const ids = array.map(item => item.id);
return new Set(ids).size !== ids.length;
}
// Example Usage:
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 1, name: 'Alicia' }
];
console.log(hasDuplicateIds(users)); // Output: true
Using some() with a Set (The Most Efficient Method)
This is the most performant method for large arrays of objects because it stops as soon as a duplicate is found, avoiding the need to create a full intermediate array with map().
The logic:
- Initialize an empty
Setto keep track of the IDs we've already seen. - Iterate through the array with
some(). - For each object, check if its ID is already in our
Set. - If it is, we've found a duplicate, and
some()returnstrue. - If it isn't, add the ID to our
Setand continue.
Solution:
function hasDuplicateIds(array) {
const seen = new Set();
return array.some(item => {
if (seen.has(item.id)) {
return true; // Found a duplicate
}
seen.add(item.id);
return false;
});
}
// Example Usage:
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 1, name: 'Alicia' }
];
console.log(hasDuplicateIds(users)); // Output: true
Conclusion
Detecting duplicates is a common problem with several clean, modern solutions in JavaScript.
- For primitive values, the
new Set(array).size !== array.lengthpattern is the most concise and readable solution. - For arrays of objects, the most performant solution is to use
some()with an externalSetto track seen values, as this avoids iterating over the entire array unnecessarily.
By choosing the appropriate method, you can write efficient and easy-to-understand code for ensuring the uniqueness of array elements.