-1

i know how to create a one dimensional empty array like this:

var data = [];
    var length = 100;
    console.log(data);
    for(var i = 0; i < length; i++) {
        data.push(' ');
    }

but how do i make the same thing, but two dimensional?

  • Welcome to Stack Overflow! Please take the [tour] (you get a badge!) and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) Your best bet here is to do your research, [search](/help/searching) for related topics on SO, and give it a go. ***If*** you get stuck and can't get unstuck after doing more research and searching, post a [mcve] of your attempt and say specifically where you're stuck. People will be glad to help. – T.J. Crowder Jul 30 '20 at 16:59
  • Can you provide example of expected output – Stefan Avramovic Jul 30 '20 at 17:01
  • 1
    Note that JavaScript doesn't have multi-dimensional arrays; what it has instead is arrays of arrays. So you create the outer array, and use nested `for` loops (for instance). In the outer loop you create the individual arrays that will be values in the outer array and push them to it; in the inner loop you add values to each inner array. – T.J. Crowder Jul 30 '20 at 17:01

2 Answers2

0

Your data is not an empty array, it is an array of 100 blanks/spaces.
If that's what you mean, then:

var length=100;
var data=[];
for(var i=0; i<length; i++) {
  var innerData=[];
  for(var j=0; j<length; j++) {
    innerData.push(' ');
  };
  data.push(innerData);
}
iAmOren
  • 2,760
  • 2
  • 11
  • 23
0

I guess what you need is an array of arrays in that case you just fill the outer array with the number of arrays you want, you could use the for loop

var data = [];
    var length = 100;
    for(var i = 0; i < length; i++) {
        data.push([]);
    }

  console.log(data)

or use fill instead as it's simpler, but the difference is all the arrays created will have same reference as the first array

array=Array(10).fill([])
console.log(array)
Sven.hig
  • 4,449
  • 2
  • 8
  • 18