GeckStar GeckStar - 16 days ago 5
Javascript Question

new Array(_).fill(object) does not create new instances of object

ES6 allows us to fill an

Array
with a certain value:

function emptyRow() {
return new Array(9).fill(0);
}


This function returns an
Array
of length 9, filled with only zeros:

>> emptyRow()
<< Array [ 0, 0, 0, 0, 0, 0, 0, 0, 0 ]


Now I want to generate an
Array
that is filled with nine of those empty rows.

function emptyMatrix() {
return new Array(9).fill(emptyRow());
}


However, instead of
fill
calling
emptyRow()
nine times, it seems to call it once and fills the new
Array
with nine references to the object created by
emptyRow()
. Naturally, if I change a value within any of those sub-arrays, the value is changed at the same index for all sub-arrays.

Is there a way to create a new object for each entry?

Answer

Array#fill won't help you, it accepts the value returned by emptyRow(), the already created object. You could use Array#map which accepts a function, although you won't be able to use the new Array() constructor. Here's the simplest way:

function emptyMatrix() {
  Array.apply(null, {length: 9}).map(emptyRow);
  // create the array            fill in values
}

Or, more generally:

function generateArray(n, valueFactory) {
  return Array.apply(null, {length: n}).map(valueFactory);
}