How to store unique values in an array in JavaScript like a boss
--
We can use Set
to store unique values in an array like a boss 💪.
The Set
object lets you store unique values of any type, whether primitive values or object references.
const colors = ['blue', 'red', 'green', 'black', 'green'];
console.log(colors); // ['blue', 'red', 'green', 'black', 'green']
const unique = Array.from(new Set(colors));
console.log(unique); // ['blue', 'red', 'green', 'black']
Set
objects are collections of values. A value in the Set
may only occur once; it is unique in the Set
's collection. You can iterate through the elements of a set in insertion order. The insertion order corresponds to the order in which each element was inserted into the set by the add()
method successfully (that is, there wasn't an identical element already in the set when add()
was called).