Sunday 5 May 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...