I have array A and I am trying to concat it to array B while array B keeps the same amount of indices.
for example:
const array_A = [1, 2, 3, 4];
const array_B = [0, 0, 0, 0, 0, 0, 0];
the result should look like this
const result = [1, 2, 3, 4, 0, 0, 0];
I tried this approach
const result = array_A.concat(array_B);
console.log(result);
but then I got array of 11 indices which I only want array of 7 indices.
[1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0];
CodePudding user response:
You could map
over the second array and check if the first array has a value at that index.
array_B.map((n, i) => array_A[i] ?? n)
If the value at an index can be null / undefined, then the ??
operator will ignore it and use the array_B
value. In that case, you can check if array_A
has that specific index using the in
opeartor
array_B.map((n, i) => i in array_A ? array_A[i] : n)
Here's a snippet:
const array_A = [1, 2, 3, 4],
array_B = [0, 0, 0, 0, 0, 0, 0],
output1 = array_B.map((n, i) => array_A[i] ?? n),
output2 = array_B.map((n, i) => i in array_A ? array_A[i] : n)
console.log(...output1)
console.log(...output2)
CodePudding user response:
You could do something like below:
const array_A = [1, 2, 3, 4];
const array_B = [0, 0, 0, 0, 0, 0, 0];
for (let i = array_A.length - 1; i >= 0; i--) {
array_B.pop()
array_B.unshift(array_A[i])
}
console.log(array_B)
Poping out last element of second array ie. array_B
using pop()
then inserting element from array_A
to array_B
from front using unshift() method. Must Loop with respect to element present in array_A
CodePudding user response:
you can use for or forEach loop on Array_A then you can replace value of Array_B with value of Array_A
const A = [1, 2, 3, 4];
const B = [0, 0, 0, 0, 0, 0, 0];
A.forEach((val, i) => {
B[i] = val;
})
console.log(B) // [ 1, 2, 3, 4, 0, 0, 0 ]