Monday, August 5, 2019

merge two arrays with a separator, javascript




I am trying to merge two arrays and have a separator included between all values (comma). I tried this:



var aAndBWithCommasInBetween = a.concat(b);


But that leads to:



DealerOrigin



instead of:



Dealer, Origin


each a and b can have many values or none.


Answer



your a and b in the example are not arrays but strings, which is why concat creates another string.




['Apple'].concat(['Orange'])
["Apple", "Orange"]


versus



"Apple".concat("Orange")
"AppleOrange"



You could be looking for array.join(), which converts an array into a single string separated by commas or whatever separator you pass in.



["Apple", "Orange"].join(',')
"Apple,Orange"

No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...