Remove Duplicates from Array in JavaScript

Learn how to remove duplicates from an array in JavaScript with Set, filter(), reduce(), and object key examples.

Published

Updated

Read time 2 min read

Reviewed byDeepak Prasad

Remove Duplicates from Array in JavaScript

Removing duplicates from an array in JavaScript is a common cleanup task when you need a unique list for display, filtering, or processing. The method you choose depends on whether you are dealing with primitives or objects.

Set, filter(), and reduce() are the most common tools for this job. If you only need a unique list of primitives, JavaScript unique array is the related topic.

Tested on: Node.js v20.18.2. A short note after each runnable snippet describes what you should see in the console.


Method 1: Remove duplicates with Set

Set keeps only unique primitive values.

javascript
const arr = [1, 2, 2, 3, 4, 4, 5];
const uniqueArr = [...new Set(arr)];
console.log("unique-set:", uniqueArr.join(","));
Output

You should see one line logging unique-set: 1,2,3,4,5.

This is the shortest solution when your array contains numbers or strings.


Method 2: Remove duplicates with filter()

The callback keeps the first occurrence of each value.

javascript
const arr = [1, 2, 2, 3, 4, 4, 5];
const uniqueArr = arr.filter((value, index, self) => self.indexOf(value) === index);
console.log("unique-filter:", uniqueArr.join(","));
Output

You should see one line logging unique-filter: 1,2,3,4,5.

Use this when you want a readable array-only solution.


Method 3: Remove duplicates from an array of objects

Object deduplication usually needs findIndex() or a Map keyed by a stable field such as id.

javascript
const people = [
  { id: 1, name: "Ana" },
  { id: 2, name: "Bea" },
  { id: 1, name: "Ana" },
];

const uniqueByFilter = people.filter((item, index, self) => index === self.findIndex((entry) => entry.id === item.id));
console.log("unique-filter:", uniqueByFilter.map((item) => item.name).join(","));
Output

You should see one line logging unique-filter: Ana,Bea.

This is the right pattern when you need a unique array of objects instead of primitive values.


Summary

To remove duplicates from an array in JavaScript, use Set for primitive values, filter() for a simple array-only approach, and key-based comparison for objects. That gives you a practical path for both unique arrays and unique arrays of objects.


Official documentation

Olorunfemi Akinlua

Boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs …