← coderrocketfuel.com

Remove All Duplicates From an Array of Strings in JavaScript

Given an array of strings, how can you remove all duplicates using JavaScript?

Below are three different methods to do that.

Set() & Spread Syntax

The first method is to create a new array using a combination of set() and spread operator syntax:

const array = ["one", "two", "three", "three", "four", "five", "one"];

const newArray = [...new Set(array)];

set() creates a new set object with only unique values from the original array. And the spread syntax (...) creates a new array that contains each string in the set.

newArray will be a new version of the array with each duplicate removed:

["one", "two", "three", "four", "five"]

Array.Filter()

Another method is using filter():

const array = ["one", "two", "three", "three", "four", "five", "one"];

const newArray = array.filter((value, index, array) => {
  return array.indexOf(value) === index;
});

The filter() method goes through each value in the array and only returns values that meet certain criteria.

For each value, we check if the first position of the element (array.indexOf(value)) in the array equals the current position (index).

If the value is a duplicate, those two index positions will be different and, therefore, will not be included in the new version of the array.

In that code example, newArray will be equal to the following:

["one", "two", "three", "four", "five"]

For Loop

You can also use a simple for() loop:

const array = ["one", "two", "three", "three", "four", "five", "one"];

const newArray = [];

for (let i=0; i < array.length; i++) {
  if (newArray.indexOf(array[i]) === -1) {
    newArray.push(array[i]);
  }
}

This uses a basic for loop that goes through each value in the original array and builds a new array. If the value has already been added to the new array, it won't be added.

In that code example, newArray will be equal to the following:

["one", "two", "three", "four", "five"]

Thanks for reading and happy coding!