JavaScript developers frequently encounter duplicate elements in arrays or collections. Duplicate removal is critical for improving performance and maintaining data integrity. In this post, we will look at many approaches for removing duplicates from an array in JavaScript, ranging from basic to advance.
When working with arrays, duplicates might occur due to user inputs, API responses, or processing issues.
Example:
const numbers = [1, 2, 3, 2, 4, 1, 5];
The purpose is to eliminate duplicate elements, which results in:
const uniqueNumbers = [1, 2, 3, 4, 5];
Let’s take a look at some of the different approaches to achieve this.
The Set object in JavaScript stores unique data, making it a simple way to remove duplicates.
const numbers = [1, 2, 3, 2, 4, 1, 5]; const uniqueNumbers = [...new Set(numbers)]; console.log(uniqueNumbers); // [1, 2, 3, 4, 5]
How It Works:
Pros:
Cons:
The reduce() method uses functional programming to remove duplicates.
const numbers = [1, 2, 3, 2, 4, 1, 5]; const uniqueNumbers = numbers.reduce((acc, value) => { if (!acc.includes(value)) { acc.push(value); } return acc; }, []); console.log(uniqueNumbers); // [1, 2, 3, 4, 5]
How It Works:
Pros:
Cons:
How It Works:
Pros:
Cons:
You may use an object to keep track of unique values when you go over the array with forEach().
const array = [1, 2, 2, 3, 4, 4, 5]; const uniqueArray = []; const seen = {}; array.forEach((value) => { if (!seen[value]) { seen[value] = true; uniqueArray.push(value); } }); console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]
How It Works:
Pros:
Cons:
Map may be used to eliminate duplicates from object arrays or to filter them based on a given property.
const users = [ { id: 1, name: "Alice" }, { id: 2, name: "Bob" }, { id: 1, name: "Alice" }, ]; const uniqueUsers = Array.from( new Map(users.map(user => [user.id, user])).values() ); console.log(uniqueUsers); // [ { id: 1, name: "Alice" }, { id: 2, name: "Bob" } ]
How It Works:
Pros:
Cons:
Understanding and adopting the appropriate approach ensures that the code is efficient, clean, and maintainable. Happy coding!
At DevelopersMonk, we share tutorials, tips, and insights on modern programming frameworks like React, Next.js, Spring Boot, and more. Join us on our journey to simplify coding and empower developers worldwide!