Eliminating Duplicate Elements from Arrays in JavaScript

September, 1st 2024 2 min read

Removing duplicate elements from arrays is a common task in JavaScript. Whether you’re cleaning user input, optimizing data, or preparing values for display, deduplication helps keep arrays clean and predictable.

Below are several practical and efficient methods to remove duplicates—from simple one‑liners to more advanced patterns for arrays of objects.

1. Using Set (Fastest and Most Common)

js
const arrayWithDuplicates = [1, 2, 3, 4, 4, 5, 6, 6, 7, 8, 8];
const uniqueArray = [...new Set(arrayWithDuplicates)];

console.log(uniqueArray);

2. Using filter() and indexOf()

js
const arrayWithDuplicates = [1, 2, 3, 4, 4, 5, 6, 6, 7, 8, 8];

const uniqueArray = arrayWithDuplicates.filter((item, index) => {
  return arrayWithDuplicates.indexOf(item) === index;
});

console.log(uniqueArray);

3. Using reduce()

js
function removeDuplicates(arr) {
  return arr.reduce((acc, curr) => {
    curr = curr.trim ? curr.trim() : curr;
    if (!acc.includes(curr)) acc.push(curr);
    return acc;
  }, []);
}

4. Using forEach() and includes()

js
const arrayWithDuplicates = [1, 2, 3, 4, 4, 5, 6, 6, 7, 8, 8];
const uniqueArray = [];

arrayWithDuplicates.forEach(item => {
  if (!uniqueArray.includes(item)) uniqueArray.push(item);
});

console.log(uniqueArray);

5. Using Map() for Arrays of Objects (Deduplicate by Key)

js
const arrayWithDuplicates = [
  { id: 1, name: "One" },
  { id: 2, name: "Two" },
  { id: 1, name: "Three" },
  { id: 3, name: "Four" },
];

const uniqueArray = [
  ...new Map(arrayWithDuplicates.map(item => [item.id, item])).values(),
];

console.log(uniqueArray);

Summary

  • Set → simplest and fastest for primitive values
  • filter + indexOf → readable and flexible
  • reduce → customizable transformation + deduplication
  • Map → best way to remove duplicates from arrays of objects

Choose the method that fits your data structure and performance needs.