return Array(n).fill(Array(n).fill(0)).map(($arrV, $i) => {$arrV.splice($i,1,1);
I want to display something similar: [[1,0,0,0,0], [0,1,0,0,0], [0,0,0,0,0], [0,0, 0,1,0], [0,0,0,0,1]]
and it fills all the arrays with units. Why?
return Array(n).fill(Array(n).fill(0)).map(($arrV, $i) => {$arrV.splice($i,1,1);
I want to display something similar: [[1,0,0,0,0], [0,1,0,0,0], [0,0,0,0,0], [0,0, 0,1,0], [0,0,0,0,1]]
and it fills all the arrays with units. Why?
The
fill()
method fills all elements of the array from the initial to the final indices with a single value.
One - in the sense of the same (in the original static value). I.e
Array(n).fill(Array(n).fill(0))
equivalent to the following:
const x = Array(n).fill(0); Array(n).fill(x)
From which it immediately follows that all elements of the result refer to the same, single value.
const f = n => Array (n).fill (Array (n).fill (0)), a = f (2) console.log (a) console.assert (a [0] !== a [1])
Therefore, the code in the map
on each pass changes the same array, which you are displeased to observe.
You can solve differently, like this:
const f = n => Array.from ({length: n}, () => Array (n).fill (0)).map ((a, i) => (a [i] = 1, a)) console.log (f (3))
This is how Array(n).fill(Array(n))
you fill the first array with the same instance of array 2
Here is a working snippet:
let n = 5; let mat = Array(n).fill(0).map(($arrV, $i) => Array(n).fill(0).fill(1, $i, $i+1)); console.log(mat)
The fact is that each of your sub-arrays in the array has the same link to each other, as a result of which, changing any of them, you change all the others. To create independent subarrays, use the Array.from()
method.
Working example:
let arr = Array(5).fill(Array(5).fill(0)); arr = arr.map(value => { return Array.from(value); }); arr.map((value, k) => { return value.splice(k, 1, 1); });
Source: https://ru.stackoverflow.com/questions/960202/
All Articles