Home > Software engineering >  Javascript 2D array filled with loop
Javascript 2D array filled with loop

Time:06-24

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

CodePudding user response:

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)

CodePudding user response:

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

  • Related