0

Why does this happen? I am trying to create a 2D array with an integer sequence. I know the alternate way to achieve the result, want to know the reason behind this behaviour. Also, using new Array(3) to fill the array shouldn't have caused any reference errors.

    let length = 3
    let arrMatrix = (new Array(3)).fill(Array(3));
    arrMatrix.fill((new Array(3)).fill(0));
    var sum = 0;
    for(let i=0; i<length; i++) {
        for(let j=0; j<length; j++) {
            arrMatrix[i][j] = sum;
            sum += 1;
        }
    }
    console.log(arrMatrix);

Output

[ [ 6, 7, 8 ], [ 6, 7, 8 ], [ 6, 7, 8 ] ]

Expected output

[ [ 0, 1, 2 ], [ 3, 4, 5 ], [ 6, 7, 8 ] ]
DrEarnest
  • 853
  • 2
  • 13
  • 27
  • you are filling with same reference. perhaps create a 1D array of 9 and chunk it to 3*3 or array.from – cmgchess May 09 '23 at 13:48
  • `const n = 3; const arr = Array.from({ length: n }, (_, i) => Array.from({ length: n }, (_, j) => i * n + j));` – mplungjan May 09 '23 at 13:54
  • or `Array.from({length: length}, (e,i) => Array(length).fill().map((_,j) => i*length+j))` https://stackoverflow.com/questions/37949813/array-fillarray-creates-copies-by-references-not-by-value – cmgchess May 09 '23 at 13:57
  • I have an alternate way to do the expected result. Can you guys explain the reason behind the above behaviours.? – DrEarnest May 09 '23 at 14:09
  • 1
    The line `arrMatrix.fill((new Array(3)).fill(0))` fills `arrMatrix` with 3 references to the same array. This means that every child of `arrMatrix` will always look the same, because they are references to the same array. – Gershom Maes May 09 '23 at 14:33

0 Answers0