0

I'm have a 2d array and I need to fill it with random values. But when I do it with a nested for loop, the values in each row are same. (example: [ [1,2,3] [1,2,3] ]). This is my code.

let grid = new Array(10);
grid.fill(new Array(10));
for (let ri = 0; ri < 10; ri++) {
    for (let ci = 0; ci < 10; ci++) {
         grid[ri][ci] = Math.random();
     }
}
// When I print this all arrays in the grid array are same
console.log(grid);

I need to know why is it and how to make all values random. Please help me. Thanks.

ChalanaN
  • 407
  • 4
  • 13
  • 2
    `grid.fill(new Array(10));` will make *a single* array and place it in all the slots in `grid`. So you have two arrays in total, you just iterate ten times over the second one and overwrite values multiple times. – VLAZ Nov 26 '20 at 07:32
  • To create an array filled with *distinct* other arrays, you can do `Array.from({length: top_level_array_size}, () => [])` – VLAZ Nov 26 '20 at 07:35
  • @VLAZ But I'm giving values for it after creating 10 arrays inside the `grid` – ChalanaN Nov 26 '20 at 07:35
  • You are *not creating 10 arrays*. `new Array(10)` creates a *single* array. Then `.fill()` places *that one single array* in 10 places. It's like doing `arr = new Array(10); grid[0] = arr; grid[1] = arr; grid[2] = arr; /*...*/ grid[9] = arr;` They all share a reference to the same array. – VLAZ Nov 26 '20 at 07:38
  • @VLAZ So in your answer, if I changed `arr` later (example:`arr = [1, 2, 3]`) So the `grid` is a array which contains 10 `[1,2,3]` in it? – ChalanaN Nov 26 '20 at 07:42
  • As @VLAZ suggested, try moving your array initialisation part inside the first loop. Sample: let grid = new Array(10); // grid.fill(new Array(10)); for (let ri = 0; ri < 10; ri++) { grid[ri] = new Array(10); for (let ci = 0; ci < 10; ci++) { grid[ri][ci] = Math.random(); } } console.log(grid); – IRSHAD Nov 26 '20 at 07:44
  • No, if you change `arr` *after* you've filled `grid`, then nothing would happen. You'd be changing what the variable references, all the slots in `grid` would still reference the old array. – VLAZ Nov 26 '20 at 07:44
  • @VLAZ So when I set `arr[0] = [1,2,3]` It doesn't change other values in the `grid`. I think I am also doing the same thing. I first initialized the array `grid` and filled it with `new Array(10)`. So the grid is now an array with 10 arrays in it. Then I changed it's values with a for loop. So I think it should not effect the other values in the `grid`. Am I right? – ChalanaN Nov 26 '20 at 07:50
  • @ChalanaN correct, if you initialise a new array for each slot, then there are no shared references. – VLAZ Nov 26 '20 at 07:52

0 Answers0