DEV Community

Cover image for How Array.fill can break arrays!
Médéric Burlet
Médéric Burlet

Posted on

4 1

How Array.fill can break arrays!

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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay