2

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

6 Answers 6

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1
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?

1 Comment

Using for loop and Array.prototype.push() on every loop it's not simple at all
1

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)

Comments

1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.