Tuesday 31 January 2017

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

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...