How to Remove Duplicates From an Array in JavaScript

Learn how to remove duplicate values from a JavaScript array using Set, filter(), and reduce(). We'll also look at arrays of objects and a few common situations you may encounter in real projects.
Have you ever worked with an array that contains the same value more than once? This can happen when collecting form data, processing API responses, or working with lists of names and IDs.
For example, you might have an array like this:
const numbers = [1, 2, 2, 3, 4, 4, 5];Here, the numbers 2 and 4 appear more than once. If you need an array containing only unique values, JavaScript provides several ways to remove those duplicates.
The simplest approach is to use Set with the spread operator. You can also use methods such as filter() and reduce() when you need more control over how duplicates are identified.
Quick Answer
The easiest way to remove duplicate values from an array in JavaScript is to use Set with the spread operator.
const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers);
// [1, 2, 3, 4, 5]A Set stores unique values, so repeated numbers are removed. The spread operator converts the result back into an array. This approach works well for primitive values such as numbers and strings.
1. Using Set to Remove Duplicates
If you want a simple way to remove duplicate values from an array, JavaScript's Set is usually the best place to start. It stores unique values, so the same primitive value will not appear more than once.
You can combine Set with the spread operator (...) to create a new array containing only unique values. You do not need to write a loop or check each value manually.
Example 1: Remove duplicate numbers
Suppose an array contains repeated numbers. Here is how you can remove them with just one line of code.
const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers);
// [1, 2, 3, 4, 5]The resulting array contains each number only once. The original order is preserved, so the values appear in the order in which they first occurred.
How does this code work?
new Set(numbers)Creates a Set from the array. Repeated number values are stored only once.
[...new Set(numbers)]The spread operator takes the values from the Set and places them into a new array.
Example 2: Remove duplicate strings
The same approach works with strings. For example, you can remove repeated fruit names from a list.
const fruits = [
"apple",
"banana",
"apple",
"orange",
"banana"
];
const uniqueFruits = [...new Set(fruits)];
console.log(uniqueFruits);
// ["apple", "banana", "orange"]Notice that the first occurrence of each fruit is retained. Set treats uppercase and lowercase strings as different values, so "Apple" and "apple" would both remain in the result.
Does Set change the original array?
No. In this example, the original array stays the same because we create a separate array for the unique values.
const numbers = [1, 2, 2, 3];
const uniqueNumbers = [...new Set(numbers)];
console.log(numbers);
// [1, 2, 2, 3]
console.log(uniqueNumbers);
// [1, 2, 3]This is useful when you still need the original data elsewhere in your application.
One important limitation
Set compares objects by reference, not by their property values. If two different objects have the same ID or name, Set will not automatically treat them as duplicates. We'll cover that situation in the section about removing duplicates from arrays of objects.
When should you use Set?
Use Set when you want to remove duplicate numbers, strings, or other primitive values from an array. It is concise, readable, and preserves the order of the first occurrence of each unique value.
Method 2: Remove Duplicates Using filter() and indexOf()
You can also remove duplicate values using JavaScript'sfilter()andindexOf()methods. This approach keeps an element only when its current index matches the index of its first occurrence.
Here is a simple example:
const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = numbers.filter((value, index) => {
return numbers.indexOf(value) === index;
});
console.log(uniqueNumbers);
// [1, 2, 3, 4, 5]How Does It Work?
filter()checks each element and keeps it only when the callback returnstrue.indexOf(value)returns the index of the first matching element in the array.- If the current index equals the first occurrence's index, the element is kept. Otherwise, the duplicate is skipped.
Example Explained
In the array [1, 2, 2, 3], the first 2 is kept because its index is 1, which matches indexOf(2). The second 2 is skipped because its index is 2, while indexOf(2) still returns 1.
Example With Strings
The same technique works with strings and other primitive values. For example, you can remove repeated fruit names while preserving their original order.
const fruits = [
"apple",
"banana",
"apple",
"orange",
"banana"
];
const uniqueFruits = fruits.filter(
(fruit, index) => fruits.indexOf(fruit) === index
);
console.log(uniqueFruits);
// ["apple", "banana", "orange"]When Should You Use This Method?
The filter() and indexOf() approach is useful when you want to understand how duplicate removal works or need a straightforward filtering example. It does not modify the original array.
Performance Consideration
This approach can take O(n²) time because indexOf() searches the array for each element. For large arrays, using Set is generally simpler and typically more efficient. Also, this indexOf() pattern does not handle NaN values the same way as Set.
Method 3: Remove Duplicates Using reduce()
JavaScript's reduce() method processes an array and combines its elements into a single result. You can use it to build a new array containing only unique values.
In this example, we use includes() to check whether a value is already in the result array.
const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = numbers.reduce((result, value) => {
if (!result.includes(value)) {
result.push(value);
}
return result;
}, []);
console.log(uniqueNumbers);
// [1, 2, 3, 4, 5]How Does It Work?
reduce()starts with an empty array, provided as the initial value.- For each element,
includes()checks whether that value already exists in the result. - If the value is not present,
push()adds it to the result array. - The callback returns the updated array for the next iteration. After processing every element,
reduce()returns the array of unique values.
Example With Strings
You can apply the same logic to arrays of strings, such as a list of fruit names. The first occurrence of each string is preserved.
const fruits = [
"apple",
"banana",
"apple",
"orange",
"banana"
];
const uniqueFruits = fruits.reduce((result, fruit) => {
if (!result.includes(fruit)) {
result.push(fruit);
}
return result;
}, []);
console.log(uniqueFruits);
// ["apple", "banana", "orange"]A Shorter reduce() Example
You can also write the same logic with a conditional expression. This version creates a new array when it encounters a new value.
const numbers = [10, 20, 10, 30, 20];
const uniqueNumbers = numbers.reduce(
(result, value) =>
result.includes(value) ? result : [...result, value],
[]
);
console.log(uniqueNumbers);
// [10, 20, 30]When Should You Use reduce()?
Use reduce() when duplicate removal is part of a larger transformation or when you want to build an accumulated result. For a simple array of unique primitive values, the Set approach is usually easier to read.
Performance Tip
Because includes() searches the accumulated array on each iteration, this approach can take O(n²) time in the worst case. For large arrays, consider using Set for a simpler and typically more efficient solution.
How to Remove Duplicate Objects From an Array
Arrays of objects are common when working with API responses, user lists, products, and other structured data. However, using Set directly does not remove separate objects just because their properties have the same values.
Why Set Does Not Remove Identical Objects
Consider two objects with the same ID and name. JavaScript treats them as different objects because each object has its own reference.
const first = { id: 1, name: "Alex" };
const second = { id: 1, name: "Alex" };
const uniqueUsers = [...new Set([first, second])];
console.log(uniqueUsers.length);
// 2The result contains two objects. To remove duplicates based on their data, choose a property that identifies each record, such as an ID.
Method 1: Use Map to Remove Objects With Duplicate IDs
A Map stores unique keys. You can use each object's ID as the key and then convert the Map values back into an array.
const users = [
{ id: 1, name: "John" },
{ id: 2, name: "Alex" },
{ id: 1, name: "John" },
{ id: 3, name: "Sara" },
{ id: 2, name: "Alex" }
];
const uniqueUsers = [
...new Map(users.map((user) => [user.id, user])).values()
];
console.log(uniqueUsers);
// [
// { id: 1, name: "John" },
// { id: 2, name: "Alex" },
// { id: 3, name: "Sara" }
// ]How It Works
users.map()creates key-value pairs using each user's ID and object.new Map()stores one value per key. If a key appears again, its value is replaced by the later object..values()retrieves the stored objects.- The spread operator converts those values into a new array.
Important: Which Duplicate Is Kept?
This Map approach keeps the last object for each ID. The position of each key in the resulting array follows its first insertion order, even when its stored value is later replaced. Use the filter() approach below if you want to keep the first matching object instead.
Method 2: Use filter() to Keep the First Object
If you want to preserve the first object for each ID, combine filter() with findIndex().
const users = [
{ id: 1, name: "John" },
{ id: 2, name: "Alex" },
{ id: 1, name: "John" },
{ id: 3, name: "Sara" }
];
const uniqueUsers = users.filter(
(user, index, array) =>
index === array.findIndex((item) => item.id === user.id)
);
console.log(uniqueUsers);
// [
// { id: 1, name: "John" },
// { id: 2, name: "Alex" },
// { id: 3, name: "Sara" }
// ]This method keeps an object only when its index matches the index of the first object with the same ID. Like the filter() and indexOf() approach, it can take O(n²) time because findIndex() searches the array for each object.
Which Method Should You Choose?
- Use Map: When you want a concise solution that keeps the last object for each key.
- Use filter() and findIndex(): When you want to keep the first object for each key.
- Choose the right key: Use a property that reliably identifies a record, such as a unique database ID.
Remove Duplicate Strings Ignoring Case
JavaScript compares strings in a case-sensitive way. That means"Apple"and"apple"are treated as different values.
To remove duplicates regardless of letter case, convert each string to a consistent case before comparing it. The following example keeps the first version of each string.
const fruits = [
"Apple",
"banana",
"APPLE",
"Banana",
"orange"
];
const uniqueFruits = fruits.filter(
(fruit, index, array) =>
index ===
array.findIndex(
(item) => item.toLowerCase() === fruit.toLowerCase()
)
);
console.log(uniqueFruits);
// ["Apple", "banana", "orange"]How It Works
toLowerCase()converts each string to lowercase for comparison.findIndex()finds the first string that matches the current string, ignoring case.filter()keeps only the first occurrence of each case-insensitive value.
A More Efficient Approach Using Set
For larger arrays, a Set can track normalized strings that have already appeared. This avoids repeatedly searching the entire array with findIndex().
const fruits = [
"Apple",
"banana",
"APPLE",
"Banana",
"orange"
];
const seen = new Set();
const uniqueFruits = fruits.filter((fruit) => {
const normalized = fruit.toLowerCase();
if (seen.has(normalized)) {
return false;
}
seen.add(normalized);
return true;
});
console.log(uniqueFruits);
// ["Apple", "banana", "orange"]Important
These examples preserve the original spelling of the first occurrence. For example, if "Apple" appears before "APPLE", the result contains "Apple". This approach is suitable for many everyday cases, but Unicode and language-specific comparisons may require more specialized normalization.
Which Method Should You Use?
JavaScript provides several ways to remove duplicate values. The right choice depends on the type of data you have, whether you need custom comparison logic, and how large the array is.
| Method | Best For | Typical Time | Preserves Order | Difficulty |
|---|---|---|---|---|
| Set | Primitive values | Typically O(n) | Yes | Easy |
| filter() + indexOf() | Simple arrays | O(n²) | Yes | Easy |
| reduce() + includes() | Custom accumulation | O(n²) | Yes | Moderate |
| Map | Objects with unique keys | Typically O(n) | Yes | Moderate |
| filter() + findIndex() | Keeping first matching object | O(n²) | Yes | Moderate |
Our Recommendation
For most arrays: Use Set
When you need to remove duplicate numbers, strings, or other primitive values, Set with the spread operator is usually the simplest option.
For arrays of objects: Use Map
When objects should be considered duplicates based on a property such as id, Map provides an efficient way to keep one object per key. Decide whether you want to keep the first or last matching object.
For custom logic: Use filter() or reduce()
These methods are useful when duplicate detection requires additional conditions or forms part of a larger data transformation. Be aware that approaches using repeated indexOf(), includes(), or findIndex() searches can take quadratic time.
Frequently Asked Questions
What is the easiest way to remove duplicates from an array in JavaScript?
The easiest way to remove duplicate primitive values is to use Set with the spread operator. For example, [...new Set([1, 2, 2, 3])] returns [1, 2, 3].
Does Set remove duplicate objects from an array?
Set removes duplicate object references, but it does not merge separate objects just because their properties are identical. To remove duplicate objects by a property such as id, use Map or filter() with a comparison.
Does removing duplicates modify the original array?
No. The common approaches shown in this article, including [...new Set(array)], filter(), and reduce() with a new accumulator array, return a new array rather than modifying the original array.
Which method is fastest for removing duplicates?
For typical arrays of primitive values, Set is generally the simplest and most efficient choice, with expected near-linear performance. Actual performance depends on the data, JavaScript engine, and implementation.
Can I remove duplicate strings regardless of letter case?
Yes. Normalize strings with toLowerCase() before checking whether a value has already appeared. This allows values such as Apple, apple, and APPLE to be treated as duplicates.
Does Set preserve the order of array elements?
Yes. Set preserves the insertion order of unique values. Converting it back to an array with the spread operator preserves that order.
How do I remove duplicate objects based on an ID?
You can create a Map using each object's ID as its key and convert the Map values back into an array. Repeated IDs replace earlier values, so this approach keeps the last object for each ID.
Conclusion
JavaScript offers several ways to remove duplicate values from an array. The best approach depends on the type of data you are working with and how you want to identify duplicates.
For most arrays containing numbers or strings, Set with the spread operator is a simple and readable solution.
const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers);
// [1, 2, 3, 4, 5]If you need more control, filter() and reduce() let you define your own filtering logic. For arrays of objects, use a property such as an ID to decide which records should be considered duplicates.
Choose the method that fits your data, preserves the order you need, and makes your code easy to understand and maintain.
Related JavaScript Tutorials
30 Days JavaScript Roadmap for Beginners
Learn JavaScript from scratch with this structured 30-day roadmap for beginners. Master variables, functions, DOM manipulation, events, APIs and build real projects.
Read tutorial →Master CSS in 30 Days: Grab Your Free Ultimate CSS Guide PDF
Download the free 30 Days CSS Series PDF. Learn CSS Flexbox, Grid, responsive design, animations, and more
Read tutorial →10 Free Web Development Tools You Should Know
Discover useful free web development tools that can help you format JSON, create code screenshots, optimize images, test websites, write CSS, and handle everyday development tasks faster.
Read tutorial →