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:
- repeated UI items
- incorrect counts
- unnecessary database writes
- extra API calls
- confusing reports or analytics
So deduplication is really a small form of data validation and cleanup.
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((value, index, array) => {
return array.indexOf(value) === index;
});
console.log(uniqueNames);
Explanation:
filter()builds a new arrayindexOf(value)returns the first position where that value appears- if the current index matches that first position, keep it
- otherwise, it is a duplicate, so skip it
Using a loop
const names = ["Mike", "Matt", "Nancy", "Adam", "Jenny", "Nancy", "Carl"];
const uniqueNames = [];
for (const name of names) {
if (!uniqueNames.includes(name)) {
uniqueNames.push(name);
}
}
console.log(uniqueNames);
This is a beginner-friendly approach because the logic is explicit.
jQuery note
jQuery does not provide a better built-in tool than modern JavaScript for this task. In current code, plain JavaScript is usually the best choice.
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 addedJennyis added- the second
Nancyis ignored because it already exists in theSet Carlis added
-
The
Setnow contains only unique values:
Set {"Mike", "Matt", "Nancy", "Adam", "Jenny", "Carl"}
- The spread operator
...copies those values into a new array:
["Mike", "Matt", "Nancy", "Adam", "Jenny", "Carl"]
So the result is a new array with duplicates removed, while preserving the order of first appearance.
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 Set(items)];
}
Common pattern: deduplicate object properties
const users = [
{ id: 1, name: "Mike" },
{ id: 2, name: "Nancy" },
{ id: 1, name: "Mike" }
];
const uniqueIds = [...new Set(users.map(user => user.id))];
console.log(uniqueIds); // [1, 2]
Developers usually prefer simple, readable code unless there is a specific performance or compatibility reason to choose another approach.
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
For primitive values like strings and numbers, this is fine. But arrays and objects are compared by reference.
const items = [{ id: 1 }, { id: 1 }];
const uniqueItems = [...new Set(items)];
console.log(uniqueItems.length); // 2
These are different object references, so they are not considered duplicates.
Mistake 4: Confusing similar-looking strings
const names = ["Nancy", "nancy", "Nancy "];
const uniqueNames = [...new Set(names)];
console.log(uniqueNames); // all may remain
If values should be treated the same, normalize them first.
Mistake 5: Using jQuery when plain JavaScript is enough
This task does not need jQuery. Modern JavaScript is shorter and clearer.
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()
- Use
Setwhen you want the clearest modern solution - Use
filter()when you want to understand how uniqueness is checked
Primitive values vs objects
| Data type | Deduplication with Set works as expected? | Example |
|---|---|---|
| Strings | Yes | "Nancy" |
| Numbers | Yes | 42 |
| Booleans | Yes | true |
| Objects | Not by property value | { id: 1 } and { id: 1 } are different references |
| Arrays | Not by content value | [1, 2] and [1, 2] are different references |
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
Setstores unique values only...converts iterable values into an array- order of first appearance is preserved
- original array is not changed unless you reassign it
Edge cases
"Nancy"and"nancy"are different strings- objects with the same content are still different if they are different references
- trim or lowercase values first if needed
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().
const uniqueNames = [...new Set(names.map(name => name.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
Abort Ajax Requests with jQuery jqXHR.abort()
Learn how to cancel an in-progress jQuery Ajax request with jqXHR.abort(), handle abort status safely, and avoid stale UI updates.
Access the Correct this Inside a JavaScript Callback
Learn why JavaScript this changes in callbacks and how to preserve an object context using bind, arrow functions, and event handler patterns.
Add Key-Value Pairs to JavaScript Objects
Learn how to add key-value pairs to JavaScript objects with dot and bracket notation, dynamic keys, examples, and common mistakes.