Categories: softare development

How to Remove Duplicates from a JavaScript Array

When working with arrays in JavaScript, you’ll often run into duplicate values. Removing them efficiently not only keeps your data clean but also makes your code more optimized. Let’s look at the most common ways of how to remove duplicates from a JavaScript array.

1. Using Set (ES6+)

const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers); // [1, 2, 3, 4, 5]

✅ Simple and efficient
✅ Best for modern JavaScript

2. Using filter() + indexOf()

const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = numbers.filter((value, index) => 
  numbers.indexOf(value) === index
);
console.log(uniqueNumbers); // [1, 2, 3, 4, 5]

✅ Works everywhere
⚠️ Slightly slower on large arrays

3. Using reduce() + includes()

const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = numbers.reduce((acc, value) => {
  if (!acc.includes(value)) acc.push(value);
  return acc;
}, []);
console.log(uniqueNumbers); // [1, 2, 3, 4, 5]

✅ Great for learning array methods

4. Using forEach() + Object Lookup

const numbers = [1, 2, 2, 3, 4, 4, 5];
const lookup = {};
const uniqueNumbers = [];

numbers.forEach(num => {
  if (!lookup[num]) {
    lookup[num] = true;
    uniqueNumbers.push(num);
  }
});

console.log(uniqueNumbers); // [1, 2, 3, 4, 5]

✅ Very fast for larger datasets

What You Should Know

The Set method is the easiest and most modern solution, but depending on the scenario (browser support, performance needs), other approaches can still be useful.

Start Learning JavaScript

Summary

How to remove duplicates from a JavaScript array is a common task with many solutions. The most modern and efficient method is using Set, while traditional methods like filter() + indexOf()reduce() + includes(), or a lookup object offer alternatives depending on performance needs and project requirements. The key takeaway: JavaScript gives you multiple tools to keep your data clean—pick the one that best fits your use case.

Recent Posts

Essential VS Code Extensions Every Developer Should Use

Visual Studio Code (VS Code) is powerful out of the box, but its real strength…

1 week ago

JavaScript Variables

1. What Is a Variable in JavaScript? A variable is a named container used to store data…

1 week ago

C++ Queue

1. What Is a Queue? A Queue is a linear data structure that follows the principle: FIFO – First…

2 weeks ago

Must-Know Angular Concepts

Angular is a full-featured frontend framework built by Google for creating large, maintainable, and high-performance web applications.…

2 weeks ago

Responsive Web Design (RWD)

What Is Responsive Web Design? Responsive Web Design (RWD) is an approach to building websites…

2 weeks ago

Geolocation API in JavaScript

The Geolocation API allows a web application to access a user’s geographical location (latitude, longitude, and more), with…

3 weeks ago