Join my Laravel for REST API's course on Udemy 👀

Remove duplicate values from a JavaScript array

July 31, 2022  ‐ 1 min read

There are multiple ways of removing duplicate values from an array in JavaScript. You can for example use the .filter() or .reduce() methods. But the most convenient way I've found is by using Sets.

Set theory is a mathematical branch, in which a set represents a collection of unique elements. Thus, each element can only occur once in a set. Perfect for the use-case of removing duplicates from an array it seems.

const values = ['Mercury', 'Venus', 'Venus', 'Earth'];
const unique = [...new Set(values)];
console.log(unique);
//=> (3) ['Mercury', 'Venus', 'Earth']

We can initialize a Set object and pass our array containing duplicate values. By using the spread operator (...) we can turn our Set object back into an array, which now only contains unique values.