How to remove duplicates from an array in JavaScript

January 09, 2020 No comments JavaScript Snippets Examples QA array duplicates

1. Introduction

In this article, we are going to face a very common problem which is removing duplicates from an array in JavaScript. We will present several solutions using easy to understand examples.

2. Using Set object

One way to remove duplicates from an array is to use Set object that stores only unique values of the specific type (primitive types or object references). Set was provided with ES6.


const colors = ["white", "green", "black", "green", "yellow", "orange", "black"];
let unique = [...new Set(colors)];

console.log(unique); // ["white", "green", "black", "yellow", "orange"]

Note that Sets are iterated in insertion order, so result array will preserve the order of the original array.

3. Using filter method

Another options is to use filter method. We can iterate over the array and, for every element check if the first position of this element is equal to the current position. These two positions will be different for duplicate elements;


const colors = ["white", "green", "black", "green", "yellow", "orange", "black"];
let unique = colors.filter((color, position) => colors.indexOf(color) == position);

console.log(unique); // ["white", "green", "black", "yellow", "orange"]

4. Using forEach iteration

Different approach to removing duplicates from an array is to iterate over each item and store in separate object elements that we already meet.


const colors = ["white", "green", "black", "green", "yellow", "orange", "black"];

const unique = (items) => {
  let seen = {};
  items.forEach(item => {
    if (!seen[item]) {
      seen[item] = true;
    }
  });
  return Object.keys(seen);
};

console.log(unique(colors)); // ["white", "green", "black", "yellow", "orange"]

5. Conclusion

In this article, we showcased the common ways to remove duplicates from an array in JavaScript. We used methods that comes from ES6 like filter, forEach and also used objects like Set or Map.
{{ message }}

{{ 'Comments are closed.' | trans }}