0

I am trying to make a 2D array javascript using looping, with a result like this:

[[a1,a2,a3,a4,a5][b1,b2....]..[...e3,e4,e5]]

I have tried multiple different things, using for loops and the below, but am unable to create as needed.

var cols = [1,2,3,4,5];
var rows = ["a", "b", "c","d", "e"];

var grid = [ for (r of rows) [ for (c of cols) r+c ] ];

any help is appreciated.

Thanks

1
  • initialize an empty array outside the loops say x. first loop rows and initialize an empty array inside first loop say 'y'. then loop cols and inside that loop push to y the sum of elements. after the second loop finish push the y to x Commented Jun 24, 2022 at 3:34

2 Answers 2

4

You can get your desired result using a nested map over the rows and columns:

var cols = [1,2,3,4,5];
var rows = ["a", "b", "c","d", "e"];

var grid = rows.map(r => cols.map(c => r + c));

console.log(grid)

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

Comments

0

It looks like @Nick beat me to it again ;-) but, obviously, this is the solution:

var cols = [1,2,3,4,5];
var rows = ["a", "b", "c","d", "e"];

const res = rows.map(r=>cols.map(c=>r+c));

console.log(res);

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.