const A = [1,2,3,4,5]
const B = [6,7,8,9,10]
const C = [];
for (let j=0; j<A.length;j++){
C[j] = C[[A[j],B[j]]
}
I want to create a 2D array C such that
C = [[1,6],[2,7],[3,8],[4,9],[5,10]]
You can use Array.prototype.map()
Code:
const A = [1,2,3,4,5]
const B = [6,7,8,9,10]
const C = A.map((item, index) => ([item, B[index]]));
console.log(C);
const A = [1,2,3,4,5]
const B = [6,7,8,9,10]
const C = [];
for (let j=0; j<A.length;j++){
C.push([A[j],B[j]]);
}
At the 5th line, we're creating an array of 2 values (one from A and one from B) and after that push the array into the A array. Very simple,NO?
for loop and Array.prototype.push() on every loop it's not simple at allneed to replace C[j] = C[[A[j],B[j]] with C[j] = [A[j],B[j]]. Because C[[A[j],B[j]] is undefined
const A = [1,2,3,4,5]
const B = [6,7,8,9,10]
const C = [];
for(let j = 0;j<A.length;j++){
C[j] = [A[j],B[j]];
}
console.log(C)
map()
const A = [1,2,3,4,5]
const B = [6,7,8,9,10]
const C = A.map((item, i) => ([item,B[i]]));
console.log(C);
What you are looking for is a transpose algorithm to switch row to column, if you take the two given arrays as a new array with rows.
const
transpose = array => array.reduce((r, a) => a.map((v, i) => [...(r[i] || []), v]), []),
a = [1, 2, 3, 4, 5],
b = [6, 7, 8, 9, 10],
c = transpose([a, b]);
console.log(c);
.as-console-wrapper { max-height: 100% !important; top: 0; }