Unwanted results when filling an array from lodash fill vs regular array
The question _.fill(Array(4), [])
is equal [[], [], [], []]
?
Because there _.isEqual(_.fill(Array(4), []), [[], [], [], []])
istrue
var test = [[], [], [], []];
test[0].push(1);
console.log(test[0]);
test[1].push(2);
console.log(test[1]);
test[2].push(3);
console.log(test[2]);
test[3].push(4);
console.log(test[3]);
returns
[1]
[2]
[3]
[4]
which I wanted but
var test = _.fill(Array(4), []);
test[0].push(1);
console.log(test[0]);
test[1].push(2);
console.log(test[1]);
test[2].push(3);
console.log(test[2]);
test[3].push(4);
console.log(test[3]);
returns
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
Am I doing it wrong? I wanted to create and populate an array of arrays in which 4
in _.fill(Array(4), [])
is dynamic.
source to share
[]
equivalent new Array()
in JS.
This means that [[], [], [], []]
is an array with 4 new arrays, and _.fill(Array(4), [])
is an array containing four copies of the same array.
In other words, the variant is _.fill
equivalent to:
var a = [];
var test = [a, a, a, a];
If you want to create a multidimensional array, you can do:
_.map(Array(n), function () { return []; })
to create a two-dimensional array.
source to share