How to Remove Array Duplicates in ES6
Published in
4 min readJan 14, 2019
Here are three ways to filter out duplicates from an array and return only the unique values. My favorite is using Set cause it’s the shortest and simplest 😁
1. Using Set
Let me start first by explaining what Set
is:
Set
is a new data object introduced in ES6. BecauseSet
only lets you store unique values. When you pass in an array, it will remove any duplicate values.
Okay, let’s go back to our code and break down what’s happening. There are 2 things going on:
- First, we are creating a new
Set
by passing an array. BecauseSet
only allows unique values, all duplicates will be removed. - Now the duplicates are gone, we’re going to convert it back to an array by using the spread operator
...
Convert Set
to an Array using Array.from
Alternatively, you can also use Array.from
to convert a Set
into an array: