// merge B to A
let A = [1, 2, 3, 4, 5];
let B = [6, 7, 8, 9, 10];
console.log("Initial A => ", A);
console.log("Initial B => ", B);
for (let i = 0; i < B.length; i ){
A[A.length i] = B[i];
}
console.log("Final A => ", A);
console.log("Final B => ", B);
I am trying to merge array A with B but in the output of Merged array its show some empty item after every new added element i am unable to find out the main reason causing it to happen, can anyone clear this scenario
CodePudding user response:
adding i to A[A.length i]
is making this problem.
just remove i and everything will be fine
let A = [1, 2, 3, 4, 5];
let B = [6, 7, 8, 9, 10];
console.log("Initial A => ", A);
console.log("Initial B => ", B);
for (let i = 0; i < B.length; i ){
A[A.length] = B[i];
}
console.log("Final A => ", A);
console.log("Final B => ", B);
CodePudding user response:
you can simply use the Array.concat() method:
let A = [1, 2, 3, 4, 5];
let B = [6, 7, 8, 9, 10];
console.log("Initial A => ", A);
console.log("Initial B => ", B);
A = A.concat(B);
console.log("Final A => ", A);
console.log("Final B => ", B);
CodePudding user response:
The problem here is that performing A[A.length i] = B[i]
will alter the length
of A
.
- Initially,
A.length
is5
. - After you append
B[0]
,A.length
is6
- When adding
B[1]
, you put it in positionA[6 1]
=A[7]
. You expected it to go in position6
, because you expected to use the originallength
of5
(plusi
of1
), butlength
is not5
anymore!
To solve this, simply don't add i
to your index of A
. Putting something in A[A.length] = ...
will always add it to the end of array A
.
Alternatively, you can use A.push(B[i])
to append each B[i]
to the end of A
, or you can avoid this code altogether by simply doing A = A.concat(B)
to append all of the elements of B
to the end of A
.