DEV Community

Justin
Justin

Posted on

JS Challenge: Remove duplicates from an array

The first method below creates a new Set object with the elements of the array which eliminates all duplicates since a Set by definition cannot have duplicate elements. Then using the Spread operator creates a new Array from the elements of the Set.

The second method uses Array filter() method to filter out multiple occurrences of the same element - keeping only the first occurrence.

const arr = [1, 1, 2, 3, 3, 4, 4, 5];

let uniqueArr = [...new Set(arr)];

// OR this works too

uniqueArr = arr.filter((value, index, self) => 
  self.indexOf(value) === index);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)