0

I would like to know why these two arrays' results differ when I assign new values to them:

let arrLiteral = [
    [0, 0, 0],
    [0, 0, 0],
    [0, 0, 0],
];

let arrFill = Array(3).fill(Array(3).fill(0));

console.log("*** BEFORE UPDATE ***");
console.log("Array Literal", arrLiteral);
console.log("Array Fill", arrFill);

let words = ["abc", "def", "g"];

for (let i = 0; i < words.length; i++) {
    for (let j = 0; j < words[i].length; j++) {
        arrLiteral[i][j] = words[i][j];
        arrFill[i][j] = words[i][j];
    }
}

console.log("*** AFTER UPDATE ***");
console.log("Array Literal", arrLiteral);
console.log("Array Fill", arrFill);

Logs look like this:

*** BEFORE UPDATE ***

Array Literal [ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ]

Array Fill [ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ]

*** AFTER UPDATE ***

Array Literal [ [ 'a', 'b', 'c' ], [ 'd', 'e', 'f' ], [ 'g', 0, 0 ] ]

Array Fill [ [ 'g', 'e', 'f' ], [ 'g', 'e', 'f' ], [ 'g', 'e', 'f' ] ]

Thanks in advance for any hints.

KamilaW
  • 199
  • 1
  • 1
  • 11
  • 1
    Think of `Array(3).fill(Array(3).fill(0));` as like doing: `const argToPass = Array(3).fill(0); Array(3).fill(argToPass)` - does that make it clearer? You only have one array that's in each spot with that approach – CertainPerformance Jun 19 '22 at 02:05
  • Yes, thank you for the comment and for the answer in the linked associated question. Now it's clear for me why it doesn't work. I've rewritten it using Array.form and it works like a charm. Thanks again! – KamilaW Jun 19 '22 at 02:50

0 Answers0