Question
How to Remove Duplicate Values from a JavaScript Array
Question
I have a simple JavaScript array that may contain duplicate values:
const names = ["Mike", "Matt", "Nancy", "Adam", "Jenny", "Nancy", "Carl"];
I want to create a new array that contains only the unique values, with duplicates removed.
I am looking for a JavaScript solution, but a jQuery-based approach would also be acceptable.
Short Answer
By the end of this page, you will understand how to remove duplicate values from a JavaScript array, why duplicates happen, and the most common ways developers create a new array of unique values. You will also learn when to use Set, filter, or a loop-based approach.
Concept
In JavaScript, arrays can contain repeated values. Removing duplicates means creating a new array where each value appears only once.
This is a common data-cleaning task. For example:
- user tags may repeat
- API responses may include duplicate IDs
- imported CSV data may contain repeated names
- form selections may need deduplication before saving
The core idea is simple: as you read through the array, keep only the first occurrence of each value and ignore later repeats.
A very common modern solution uses Set.
const names = ["Mike", "Matt", "Nancy", "Adam", "Jenny", "Nancy", "Carl"];
const uniqueNames = [...new Set(names)];
console.log(uniqueNames);
// ["Mike", "Matt", "Nancy", "Adam", "Jenny", "Carl"]
Why this works:
Setis a built-in JavaScript object that stores unique values only- when duplicate values are added, they are automatically ignored
- spreading with
...turns theSetback into an array
This matters in real programming because duplicate data can cause:
Mental Model
Think of a Set like a guest list at an event.
- The first time
Nancyarrives, her name is added to the list. - The second time
Nancyarrives, the list checks and says, "She is already on the list," so nothing changes.
An array is like a line of people where duplicates are allowed.
A Set is like a checked-in list where each name can appear only once.
When you remove duplicates from an array, you are essentially passing the array through a "unique-only filter."
Syntax and Examples
Modern approach with Set
const names = ["Mike", "Matt", "Nancy", "Adam", "Jenny", "Nancy", "Carl"];
const uniqueNames = [...new Set(names)];
console.log(uniqueNames);
Output:
["Mike", "Matt", "Nancy", "Adam", "Jenny", "Carl"]
This is the shortest and most readable solution in modern JavaScript.
Using filter() and indexOf()
const names = ["Mike", "Matt", "Nancy", "Adam", "Jenny", "Nancy", "Carl"];
const uniqueNames = names.filter( {
array.(value) === index;
});
.(uniqueNames);
Step by Step Execution
Consider this example:
const names = ["Mike", "Matt", "Nancy", "Adam", "Jenny", "Nancy", "Carl"];
const uniqueNames = [...new Set(names)];
Step by step:
-
JavaScript reads the array:
MikeMattNancyAdamJennyNancyCarl
-
new Set(names)is created.Mikeis addedMattis addedNancyis addedAdamis added
Real World Use Cases
Cleaning API data
An API might return repeated category names:
const categories = ["books", "music", "books", "games"];
const uniqueCategories = [...new Set(categories)];
Building dropdown options
If product sizes are repeated, you may want only unique options in a select menu.
Preventing duplicate tags
When users add tags to a post, duplicates should usually be removed before saving.
Importing spreadsheet data
CSV or Excel imports often contain repeated rows or repeated identifiers that need cleanup.
Analytics and reporting
You may want unique users, unique countries, or unique event types before calculating counts.
Real Codebase Usage
In real projects, developers often remove duplicates as part of a larger data-processing step.
Common pattern: normalize then deduplicate
const names = [" Mike ", "mike", "Nancy", "nancy"];
const uniqueNames = [...new Set(names.map(name => name.trim().toLowerCase()))];
This is useful when values look different but should be treated as the same.
Common pattern: validate before storing
function saveTags(tags) {
const uniqueTags = [...new Set(tags)];
// save uniqueTags
}
Common pattern: guard clause for invalid input
function uniqueValues(items) {
if (!Array.isArray(items)) {
return [];
}
return [...new (items)];
}
Common Mistakes
Mistake 1: Expecting the original array to change automatically
const names = ["Mike", "Nancy", "Nancy"];
[...new Set(names)];
console.log(names); // still unchanged
Set creates a new value. If you want the result, store it:
const uniqueNames = [...new Set(names)];
Mistake 2: Forgetting to convert the Set back to an array
const uniqueNames = new Set(names);
console.log(uniqueNames);
This gives you a Set, not an array. Convert it when needed:
const uniqueNames = [...new Set(names)];
Mistake 3: Using indexOf() carelessly with complex values
Comparisons
| Approach | Example | Best for | Notes |
|---|---|---|---|
Set | [..., new Set(arr)] | Modern JavaScript and readability | Shortest and most common |
filter() + indexOf() | arr.filter((v, i, a) => a.indexOf(v) === i) | Learning how duplicate detection works | More verbose |
Loop + includes() | for...of with includes() | Beginners who want explicit logic | Easy to understand |
Set vs filter()
Cheat Sheet
Quick syntax
const uniqueArray = [...new Set(array)];
Example
const names = ["Mike", "Matt", "Nancy", "Adam", "Jenny", "Nancy", "Carl"];
const uniqueNames = [...new Set(names)];
Alternative with filter()
const uniqueArray = array.filter((value, index, arr) => arr.indexOf(value) === index);
Alternative with loop
const uniqueArray = [];
for (const item of array) {
if (!uniqueArray.includes(item)) {
uniqueArray.push(item);
}
}
Important rules
FAQ
How do I remove duplicates from an array in JavaScript?
The simplest modern way is:
const uniqueArray = [...new Set(array)];
Does Set preserve the original order?
Yes. It keeps values in the order they first appear.
Can I remove duplicates without using Set?
Yes. You can use filter() with indexOf() or a loop with includes().
Does this work for arrays of objects?
Not automatically by object content. Set compares object references, not their internal property values.
Is jQuery needed to remove duplicates from an array?
No. Plain JavaScript is enough and is usually the better choice.
Does removing duplicates change the original array?
No, unless you assign the result back to the same variable.
How do I treat "Nancy" and "nancy" as duplicates?
Normalize the values first, for example with toLowerCase().
Mini Project
Description
Build a small utility that cleans a list of user-submitted tags. In real applications, users often enter duplicate tags with different spacing or capitalization. This project demonstrates how to normalize values and remove duplicates before storing or displaying them.
Goal
Create a function that takes an array of tags, normalizes them, removes duplicates, and returns a clean array.
Requirements
- Accept an array of strings as input.
- Remove extra spaces from each tag.
- Convert each tag to lowercase.
- Remove duplicate tags.
- Return the cleaned array.
Keep learning
Related questions
Deep Cloning Objects in JavaScript: Methods, Trade-offs, and Best Practices
Learn how to deep clone objects in JavaScript, compare structuredClone, JSON methods, and recursive approaches with examples.
Get Screen, Page, and Browser Window Size in JavaScript
Learn how to get screen size, viewport size, page size, and scroll position in JavaScript across major browsers with clear examples.
How JavaScript Closures Work: A Beginner-Friendly Guide
Learn how JavaScript closures work with simple explanations, examples, common mistakes, and practical use cases for real code.