0

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?

GeckStar
  • 1,136
  • 1
  • 14
  • 22

5 Answers5

2

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);
}
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
1

An other solution with map():

var line = new Array(9).fill(0);
var matrix = line.map(x => new Array(9).fill(0))
console.log(matrix);
kevin ternet
  • 4,514
  • 2
  • 19
  • 27
0

function emptyMatrix(length) {
  var matrix = new Array();
  for (var i = 0; i < length; i++)
    matrix[i] = new Array(length).fill(0)
  return matrix

}
console.log(emptyMatrix(5))

You can set length of your matrix

mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

You can use Array.from() to create arrays of any length you want, and initialize them:

const createMatrix = (x, y) => Array.from({ length: x }, () =>
  Array.from({ length: y }, () => 0)
);

const result = createMatrix(9, 5);

console.log(result);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

You can use Array.from() to generate an array of specific length, and then Array.prototype.map() to fill it with empty rows:

const emptyRow = () => Array(9).fill(0);

const generateArray = (n, valueFactory) => Array.from({length: 9}).map(valueFactory);

console.log(generateArray(9, emptyRow));
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177