Node: Matrices in Objects

Created on 10 Oct 2018  路  5Comments  路  Source: nodejs/node

Hello team,

I'm a little confused about this. What am I doing wrong ?

Grids = {}

// I have to init matrix, fill cells with 0
Grids['grid_1'] = new Array(5).fill(new Array(5).fill(0))

// And here, just update a cell's value
// The cell x = 1, y = 3 in the grid ['grid_1'] should take => 1
Grids['grid_1'][1][3] = 1

// But, it doesn't works this way
console.log(Grids)

// I have this instead
grid_1: Array(5)
        0: (5) [0, 0, 0, 1, 0]
        1: (5) [0, 0, 0, 1, 0]
        2: (5) [0, 0, 0, 1, 0]
        3: (5) [0, 0, 0, 1, 0]
        4: (5) [0, 0, 0, 1, 0]

Thanks

Most helpful comment

It's totally normal. You fill your first array with the same array.
new Array(5).fill(0) will return one new array, and you put this array in [0], [1], [2], ... So if you change it with Grids['grid_1'][1][3] = 1, you change this unique array, so you have the modification in all keys of grid_1.

Like said before, you have to create a new Array for each index (with a .map for example)

All 5 comments

I think you can drop .fill

Grids['grid_1'] = Array.apply(null, {length: 5}).map(() => Array(5).fill(0))

@phareal feel free to close the issue if your problem is solved 馃槈

It's totally normal. You fill your first array with the same array.
new Array(5).fill(0) will return one new array, and you put this array in [0], [1], [2], ... So if you change it with Grids['grid_1'][1][3] = 1, you change this unique array, so you have the modification in all keys of grid_1.

Like said before, you have to create a new Array for each index (with a .map for example)

You can also use Array.from() with array-like object and map function argument:

Grids['grid_1'] = Array.from({length: 5}, row => new Array(5).fill(0));

Or, because Array.from() does not ignore holes, this also suffices:

Grids['grid_1'] = Array.from(new Array(5), row => new Array(5).fill(0));

Nice thanks.

Was this page helpful?
0 / 5 - 0 ratings