How to Prevent Adding Duplicates to an Array in JavaScript
When managing a list of items, a common requirement is to ensure that the list contains only unique values. Whether you're adding items to a shopping cart, managing a list of tags, or tracking user IDs, you need a reliable way to prevent duplicate entries.
This guide will teach you two primary methods for achieving this. We will cover the standard approach of checking an array for an item's existence before adding it, and the more modern and often superior approach of using a Set object, which is specifically designed to store unique values.
Method 1: Checking Before Adding to an Array
The most direct way to maintain a unique array is to check if an element already exists before you push() a new one. The Array.prototype.includes() method is the perfect tool for this.
For example, you have an array and want to add a new item, but only if it's not already in the list.
// Problem: How to add 'new_item' only if it's not a duplicate?
let items = ['apple', 'banana', 'cherry'];
let newItem = 'banana'; // This is a duplicate
Solution:
function addUnique(array, item) {
// Check if the item is NOT already in the array
if (!array.includes(item)) {
array.push(item);
}
}
let items = ['apple', 'banana', 'cherry'];
addUnique(items, 'banana'); // 'banana' is already present, nothing happens
console.log(items); // Output: ['apple', 'banana', 'cherry']
addUnique(items, 'date'); // 'date' is new, so it gets added
console.log(items); // Output: ['apple', 'banana', 'cherry', 'date']
This method is simple, readable, and effectively prevents duplicates.
Method 2 (Recommended): Using a Set for Uniqueness
While the first method works well, if the core requirement of your collection is to always be unique, then an Array might not be the right tool for the job. A Set is a native JavaScript data structure that is specifically designed to store a collection of unique values.
The logic: A Set automatically handles uniqueness for you. When you try to .add() an element that already exists, it simply does nothing.
Solution:
let uniqueItems = new Set(['apple', 'banana', 'cherry']);
console.log(uniqueItems); // Output: Set(3) { 'apple', 'banana', 'cherry' }
// Try to add a duplicate item
uniqueItems.add('banana'); // Nothing happens, as 'banana' is already in the Set
console.log(uniqueItems); // Output: Set(3) { 'apple', 'banana', 'cherry' }
// Add a new item
uniqueItems.add('date');
console.log(uniqueItems); // Output: Set(4) { 'apple', 'banana', 'cherry', 'date' }
Using a Set is often the cleaner and more semantically correct approach when your primary goal is to maintain a unique collection of items. If you need an array at the end, you can easily convert it: const finalArray = Array.from(uniqueItems);.
Use Case: Removing Duplicates from an Existing Array
A related task is to take an existing array that already contains duplicates and produce a new array with only the unique values. The Set object makes this a simple one-liner.
Example of the problem:
// Problem: How to get a unique list from this array?
let duplicateArray = ['a', 'b', 'a', 'c', 'b', 'a'];
Solution:
let duplicateArray = ['a', 'b', 'a', 'c', 'b', 'a'];
// 1. Create a Set from the array to automatically remove duplicates.
// 2. Convert the Set back into an array.
let uniqueArray = [...new Set(duplicateArray)];
console.log(uniqueArray); // Output: ['a', 'b', 'c']
This is the most modern and concise way to de-duplicate an array in JavaScript.
Preventing Duplicate Objects in an Array
The methods above work for primitive values (strings, numbers). For objects, the includes() method and Set check for reference equality, not structural equality. Two different objects with the same properties are not considered duplicates.
Example of the problem:
// Problem: How to prevent adding an object with a duplicate 'id'?
const users = [{ id: 1, name: 'Alice' }];
const newUser = { id: 1, name: 'Alicia' }; // Duplicate ID
Solution: you must manually check for the property you care about using a method like some().
function addUniqueUser(array, user) {
// Check if any user in the array already has this ID
const isDuplicate = array.some(existingUser => existingUser.id === user.id);
if (!isDuplicate) {
array.push(user);
}
}
const users = [{ id: 1, name: 'Alice' }];
addUniqueUser(users, { id: 1, name: 'Alicia' }); // Duplicate ID, not added
addUniqueUser(users, { id: 2, name: 'Bob' }); // New ID, is added
console.log(users); // Output: [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' } ]
Conclusion
Preventing duplicate entries in a collection is a common task with clear, modern solutions.
- If you are working with an
Array, the best practice is to check for an item's existence before adding it:if (!array.includes(item)) { array.push(item); }. - If the primary purpose of your collection is to guarantee uniqueness, the
Setobject is the more appropriate and idiomatic data structure to use from the start. - For arrays of objects, you must perform a manual check (e.g., using
some()) based on a unique property like anid.