1

I have two arrays A and B, both of which contain lots of elemets and look like this:

var A = ["A", "B", "C", "D"];
var B = [1, 2, 3, 4];

Now I want an array C that "merges" A and B by concatenating them in alternating sequence so that

C = ["A", 1, "B", 2, "C", 3, "D", 4]

I tried this:

for (var i = 0; p < 3; i++) {
    C = A[i].concat(B[i])
}

But this results in C = "D4".

How can I achieve that I merge two arrays in by alternately choosing one element of each array?

ben_aaron
  • 1,504
  • 2
  • 19
  • 39

3 Answers3

2

You can use reduce and concat together for this:

var A = ["A", "B", "C", "D"];
var B = [1, 2, 3, 4];

var result = A.reduce(function(prev, curr) {
    return prev.concat(curr, B[prev.length / 2]);
}, []);

alert(result);

Or simply for or forEach loop:

var result = [];
A.forEach(function(el, i) {
    result.push(el, B[i]);
});

will produce the same result.

dfsq
  • 191,768
  • 25
  • 236
  • 258
2
var C = [];
for (var i = 0; p < 3; i++) {
  C.push(A[i]);
  C.push(B[i]);
}
Jorge
  • 227
  • 1
  • 3
1
var l = A.length + B.length,
    C = Array(l);
for(var i=0; i<l; ++i)
    C[i] = (i%2 ? B : A)[i/2|0];

Basically, it fills C with items from A or B depending on if i is even or odd.

Note I used i/2|0 as a shortcut, but it will only work i l is strictly less than 231. If you want to be safe, use Math.floor(i/2).

Oriol
  • 274,082
  • 63
  • 437
  • 513