Home > other >  how my array contains empty item after merging?
how my array contains empty item after merging?

Time:08-20

// 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.

  1. Initially, A.length is 5.
  2. After you append B[0], A.length is 6
  3. When adding B[1], you put it in position A[6 1] = A[7]. You expected it to go in position 6, because you expected to use the original length of 5 (plus i of 1), but length is not 5 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.

  • Related