How to Remove Duplicate Elements from an Array in JavaScript

When working with arrays in JavaScript, you might encounter situations where you need to remove duplicate elements. This is a common task, and there are several efficient ways to achieve it. In this article, we’ll explore different methods to remove duplicates from an array, ranging from simple techniques to more advanced approaches.

1. Using Set

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

console.log(uniqueArray); // Output: [1, 2, 3, 4, 5, 6, 7, 8]

2. Using filter() and indexOf()

ts
123456
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); // Output: [1, 2, 3, 4, 5, 6, 7, 8]

3. Using reduce()

ts
12345678910
function removeDuplicates(arr: string[]): string[] {
  const unique = arr.reduce(function (acc, curr) {
    curr.trim();
    if (!acc.includes(curr)) {
      acc.push(curr);
    }
    return acc;
  }, []);
  return unique;
}

4. Using forEach() and includes()

ts
12345678910
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); // Output: [1, 2, 3, 4, 5, 6, 7, 8]

5. Using Map

ts
1234567891011121314151617
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);
// Output: [
//   { id: 1, name: 'Alice' },
//   { id: 2, name: 'Bob' },
//   { id: 3, name: 'Charlie' }
// ]