0

*Please open your browser console to see the log of the table.

const n = 5;
const m = 4;
const vl = new Array(n).fill(Array.from({length: m}, (v, i) => false))
console.table(vl)
vl[0][0] = true
console.table(vl)

I was trying to change only one value of [0][0], but it is changing the whole column as true.

Not sure what's happening behind the scene. Maybe is it related to 2d array initialization?

enter image description here

tpikachu
  • 4,478
  • 2
  • 17
  • 42
  • 1
    this is happening as the reference is same. try with this: `Array.from({length:n}, ()=>Array.from({length: m}, (v, i) => false))` – gorak Oct 03 '22 at 14:30

1 Answers1

1

just use Array.from two times and you are good to go

const n = 5;
const m = 4;
const vl = Array.from({length: n}, () =>Array.from({length: m}, (v, i) => false))
console.table(vl)
vl[0][0] = true
console.log(vl)
R4ncid
  • 6,944
  • 1
  • 4
  • 18