DEV Community

Ayrton
Ayrton

Posted on

#Trick - Merge a JS array with 1 line of code (not as simple)

Hey Tricks Hunter !
Many thanks to your feedback about my last post ! your so awesome !
https://dev.to/simerca/why-you-don-t-use-gitlab-430j

I have worked on a project, we do make an automatic legend on a map based on markers colors.

and the output of all markers colors repeat sometimes in array ex :

colors = ['rgb(0,255,0)','rgb(0,255,0)','rgb(0,255,0)','rgb(0,255,0)','rgb(0,0,255)','rgb(0,255,0)']
Enter fullscreen mode Exit fullscreen mode

Let me know you, how to merge this array simply with a simple JS function.

let array = ['a','a','b','b','c','c'];
let mergedArray = [...new Set(array)];
// output ['a','b','c'];
Enter fullscreen mode Exit fullscreen mode

The most important thing is ... is the new decomposition synthax in JS. If you use this, you set the variable content inside another.

exemple with object:

let datas = {
   age:27,
   gender:robot,
}

let users = {
  email:xxx@xxx.com,
  datas:...datas
}

// output :

{
  email:xxx@xxx.com,
  datas:{
    age:27,
    gender:robot,
  }
}
Enter fullscreen mode Exit fullscreen mode

So if you combine
... and new Set() you do the trick with on line of code !
Cool no ?

Top comments (1)

Collapse
 
simerca profile image
Ayrton

Dont forget to discuss with me because I love cat. 😸