loading...
Cover image for How Array.fill can break arrays!

How Array.fill can break arrays!

crimsonmed profile image Médéric Burlet ・2 min read

Introduction

When working with arrays one should always be very careful in the difference between Array.from and Array.fill.

Array.fill

It is very tempting to you Array.fill as it has a much simpler syntax. However it is a nasty little beast when it comes to multi-dimensional array

Array.fill actually references the same object in memory.

What does this mean?

lets create a 5*5 multi dimensional array. This could be used for generating video games based on a cell system.

let test = new Array(5).fill(new Array(5).fill("1"))
console.log(test)

This gives us the following output:

[
  [ '1', '1', '1', '1', '1' ],
  [ '1', '1', '1', '1', '1' ],
  [ '1', '1', '1', '1', '1' ],
  [ '1', '1', '1', '1', '1' ],
  [ '1', '1', '1', '1', '1' ]
]

Everything seems pretty ok until the moment we try to modify just one cell:

test[0][1] = "5"
console.log(test)

This gives us the following output:

[
[ '1', '5', '1', '1', '1' ],
[ '1', '5', '1', '1', '1' ],
[ '1', '5', '1', '1', '1' ],
[ '1', '5', '1', '1', '1' ],
[ '1', '5', '1', '1', '1' ]
]

WAIT WHAT???

Well by referencing the same object in memory that means all the cells in one column will change when changing one!

Array.from to the rescue

Array.from has a more iterative approach and does not reference same objects this means we will be able to modify anything.

let fixed = Array.from({length: 5}, () => (
    Array.from({length: 5}, () => ("1"))
))
console.log(fixed)

This gives us the following output:

[
  [ '1', '1', '1', '1', '1' ],
  [ '1', '1', '1', '1', '1' ],
  [ '1', '1', '1', '1', '1' ],
  [ '1', '1', '1', '1', '1' ],
  [ '1', '1', '1', '1', '1' ]
]

For now it looks the same but if we try to modify a cell:

fixed[0][1] = "5"
console.log(fixed)

We get the following output:

[
  [ '1', '5', '1', '1', '1' ],
  [ '1', '1', '1', '1', '1' ],
  [ '1', '1', '1', '1', '1' ],
  [ '1', '1', '1', '1', '1' ],
  [ '1', '1', '1', '1', '1' ]
]

WOHOOO

Now we can create real multi-dimensional arrays


Burlet Mederic
https://medericburlet.com
https://mederic.me
https://twitter.com/crimson_med

Discussion

pic
Editor guide