1

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.

devdropper87
  • 4,025
  • 11
  • 44
  • 70

3 Answers3

3

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"
  • https://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript-and-de-duplicate-items/36146642#36146642 – Zigri2612 Mar 22 '16 at 05:18
2
a=[1,2]
  [1, 2]
b=[3,5]
  [3, 5]
a.concat(b)
[1, 2, 3, 5]

It works fine. This is what I tried in the console.

If you trya+b,then You will get

 1,23,5
Gibbs
  • 21,904
  • 13
  • 74
  • 138
  • https://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript-and-de-duplicate-items/36146642#36146642 – Zigri2612 Mar 22 '16 at 05:19
1
var aAndBWithCommasInBetween = a.concat(b).join(',');
Jason Fetterly
  • 182
  • 1
  • 12