3

I created a 2d array using Array constructor and filling it with a array inside it.

const a = new Array(26).fill(new Array(2).fill(-1));

When i try to do this a[0][0] = 0 the 0th index of all 26 arrays have changed. How do I prevent that?

const a = new Array(26).fill(new Array(2).fill(-1));
a[0][0] = 0

console.log(a)
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 1
    That's quite intriguing... – DecPK Sep 12 '21 at 06:30
  • 1
    [_"If the first parameter is an object, each slot in the array will reference that object."_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill). – Andy Sep 12 '21 at 06:33
  • `Array.from({ length: 26 }, () => new Array(2).fill(-1))` This will also work – DecPK Sep 12 '21 at 06:40

1 Answers1

1

Try this:

const a = [...Array(26)].map(() => new Array(2).fill(-1))
a[0][0] = 0

console.log(a)
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46