简体   繁体   中英

Merge two arrays in alternating sequence in Jquery

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?

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.

var C = [];
for (var i = 0; p < 3; i++) {
  C.push(A[i]);
  C.push(B[i]);
}
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 2 31 . If you want to be safe, use Math.floor(i/2) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM