Reputation: 158
I have 2 dynamic arrays of HTML elements
let's say that there is array A = [1, 2 , 3], and array B = [4, 5, 6, 7, 8] (they have different lengths that can change in time)
I need a way to merge them both to create array C, so that array C will be a mixture of 1 element from A, then 1 element from B, then one from A .. and so on till they're both done.
Ex: I need array C = [1, 4, 2, 5 , 3 , 6 , 7 , 8]
Is there a way for me to do that using javascript or jquery?
Upvotes: 1
Views: 349
Reputation: 26844
One option is to use the classic for
loop. Use Math.max
to get the higher length.
let A = [1, 2, 3];
let B = [4, 5, 6, 7, 8];
let C = [];
for (i = 0; i < Math.max(A.length, B.length); i++) {
if (A[i]) C.push(A[i]); //Push if A[i] exist
if (B[i]) C.push(B[i]); //Push if B[i] exist
}
console.log(C);
Will also work if A
has more array elements than B
let A = [1, 2, 3, 4, 5, 6, 7];
let B = [8, 9, 10];
let C = [];
for (i = 0; i < Math.max(A.length, B.length); i++) {
if (A[i]) C.push(A[i]);
if (B[i]) C.push(B[i]);
}
console.log(C);
Upvotes: 2
Reputation: 23859
You can loop over the larger array and push the elements to results from both the arrays in the iteration. Here is a way:
var A = [1, 2, 3];
var B = [4, 5, 6, 7, 8];
var result = B.reduce((a, item, i) => {
if (A[i]) {
a.push(A[i]);
}
a.push(item);
return a;
}, []);
console.log(result);
Upvotes: 0