How to update only the given index of 2d array in javascript?

Viewed 31

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)

1 Answers

Try this:

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

console.log(a)

Related