loading...

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

simerca profile image Ayrton ・1 min read

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)']

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'];

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,
  }
}

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

Posted on by:

simerca profile

Ayrton

@simerca

J'aime faire des choses inutiles 😅

Discussion

pic
Editor guide
 

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