Remove Duplicates from array JavaScript
Introduction
In this article, we will learn how to remove duplicates from an array in JavaScript using various techniques. Whether you are a beginner or an experienced developer, you will find practical examples and detailed explanations to remove duplicates easily and efficiently. I will show you multiple approaches to meet every need, from modern and fast solutions to more basic ones.
Techniques to Remove Duplicates from an Array in JavaScript
1. Use Set() to Remove Duplicates (The Easiest Method)
The fastest way to remove duplicates is by using the Set
object, which does not allow duplicate values.
Hereβs how to do it:
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]
Explanation:
Set
converts the array into a collection of unique values.- The spread operator (
...
) converts the set back into a standard array.
2. Remove Duplicates with filter() and indexOf()
Another solution is to use the filter()
method along with indexOf()
.
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = array.filter((item, index) => array.indexOf(item) === index);
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]
Explanation:
filter()
iterates over each element in the array.indexOf(item)
returns the index of the first occurrence ofitem
. If the current index matches the first occurrence, the element is unique.
3. Method with reduce()
You can also use reduce()
to build a new array without duplicates.
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = array.reduce((acc, item) => {
if (!acc.includes(item)) {
acc.push(item);
}
return acc;
}, []);
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]
Explanation:
reduce()
accumulates the result inacc
(accumulator).- It checks if the element already exists in
acc
usingincludes()
.
4. Approach with forEach()
For a more customized control, you can use forEach()
.
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = [];
array.forEach(item => {
if (!uniqueArray.includes(item)) {
uniqueArray.push(item);
}
});
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]
Explanation:
forEach()
iterates through each element and checks if it already exists inuniqueArray
.
Which Method Should You Choose?
The choice of method depends on the context:
Set()
: The simplest and fastest for most cases.filter()
andindexOf()
: Useful for a deeper understanding of how arrays work.reduce()
: Powerful and flexible.forEach()
: Ideal for customizing the behavior during iteration.
Conclusion
Removing duplicates from an array in JavaScript is a common task that you can handle in various ways. If you are a beginner, start with Set()
. As you gain experience, try other methods to understand which one best suits your needs.