0

I want to create a two dimensionals array in JavaScript but I have some problems.

I don't understand why those two functions (which just create a two dimensionals Array with a defined size) don't work the same way.

function createArray(size) {
    const arr = new Array(size);
    for (let i = 0; i < size; ++i) {
        arr[i] = new Array(size).fill(false);
    }
    return arr;
}

function createArrayFill(size) {
    return new Array(size).fill(new Array(size).fill(false));
}

const array = createArray(3);
const arrayFill = createArrayFill(3);

console.log(array);
console.log(arrayFill);

array[1][1] = true;
arrayFill[1][1] = true;

console.log(array);
console.log(arrayFill);

Here is the output:

[ [ false, false, false ],
[ false, false, false ],
[ false, false, false ] ] // array OK

[ [ false, false, false ],
[ false, false, false ],
[ false, false, false ] ] // arrayFill OK

[ [ false, false, false ],
[ false, true, false ],
[ false, false, false ] ] // array OK

[ [ false, true, false ],
[ false, true, false ],
[ false, true, false ] ] // arrayFill FAIL

As we can see, both arrays are filled well: with only "false".

For both array we put the [1][1] to "true" but in the second one, it puts every cell of the second column to "true".

Do you know why?

I don't understand why both console.log display the same array but the same code don't do the same result.

(I am using node.js v7.1.0 to test the code)

GG.
  • 21,083
  • 14
  • 84
  • 130
lludol
  • 55
  • 3
  • 11
  • As @TedHopp answered, you are filling the array with the same object. If you want to avoid it, use `Array.from` function: `const arrayFill = Array.from(Array(size), e => Array.from(Array(size), e => false));` – Alan Vinícius Feb 14 '20 at 02:38

1 Answers1

4

In the second case, you are filling the outer array with the same Array object in every row.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • Ok, thank you. It's weird that the `console.log` display the same array. – lludol Dec 22 '16 at 16:24
  • @lludol - What's weird about it? Since (in the second case) the same array object is in each position of the outer array, `console.log` simply displays the same array over and over as it iterates through the outer array. – Ted Hopp Dec 22 '16 at 16:57