Isaac
Isaac

Reputation: 396

Create a 2D array from paired elements of two 1D arrays in JavaScript

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]]

Upvotes: 2

Views: 383

Answers (6)

Nina Scholz
Nina Scholz

Reputation: 386578

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; }

Upvotes: 1

Maheer Ali
Maheer Ali

Reputation: 36574

need 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)

Better way: using 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);

Upvotes: 1

Code Maniac
Code Maniac

Reputation: 37755

You just need to C[[A[j],B[j]] correct this line. By this line you're trying to access an index [A[j],B[j]] in C which is ( undefined ) not what you want

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)

Upvotes: 1

Taohidul Islam
Taohidul Islam

Reputation: 5414

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?

Upvotes: 1

Yosvel Quintero
Yosvel Quintero

Reputation: 19070

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);

Upvotes: 1

Artee
Artee

Reputation: 834

Try this:

const A = [1,2,3,4,5]
const B = [6,7,8,9,10]
const C = A.map((_,i)=>[A[i],B[i]])
console.log(C);

Upvotes: 1

Related Questions