A Unique JavaScript Array
One unfortunate thing about JavaScript is that it doesn’t have a uniq
method like Ruby.
Yes, we can write our own uniq method using filter... but what if we need something quick and easy that we only plan on using once for testing or a small project? We can do the same with less code using Set
!
The
Set
object lets you store unique values of any type, whether primitive values or object references.
Set
objects are collections of values. You can iterate through the elements of a set in insertion order. A value in theSet
may only occur once; it is unique in theSet
's collection.
Neat! Let’s try it out.
var array = [0, 1, 1, 0, 0, 'one', 'zero', 'one']console.log([...new Set(array)])
Logged in the console is our result: [0, 1, 'one', 'two']
. Everything looks great!
Could you think of how we can change this code to make it dynamic and reusable?