A Unique JavaScript Array

Chindalath Traymany
1 min readMar 1, 2021

--

Photo by Jessica Ruscello on Unsplash

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.

Description

Set objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set may only occur once; it is unique in the Set'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?

--

--

Chindalath Traymany
Chindalath Traymany

Written by Chindalath Traymany

Laotian-American woman pursuing my passion for mentally stimulating and complex problem-solving through programming.

No responses yet