UI developer tutorials and guides

Wednesday, June 22, 2022

Quickly remove duplicates from array in Javascript

 Suppose we have array with duplicate values. How do we remove then duplicates? I remember Python have simplest way for that and JavaScript have such capabilities too.

let langs=["Vuejs","Angular",Vuejs",Reactjs","Solidjs","Reactjs"];

Here we have duplication values. To remove them, we can looping through each item. There is another way.

Set

Unlike array Sets only store unique values. So lets convert our array to Set with constructor.

const myset= new Set(langs)

 Remember set object will look like the following

{"Angular",Vuejs",Reactjs","Solidjs"}

Back to array

We have to put the values back to array using the spread operator.

langs=[...myset]

Read more JavaScript tips @ JSSU

 

0 comments:

Post a Comment