Home > Mobile >  Why does for loop nested in map() function return an array of side NxN^2 instead of NxN?
Why does for loop nested in map() function return an array of side NxN^2 instead of NxN?

Time:08-13

I am simply trying to initialize a 2D array of size N x N - where N = the boardSize prop - but when I write out the following, I instead get a 2D array of size N x N^2:

let cells = new Array(this.props.boardSize).fill([]).map((e) => {
  let newRow = e;
  for (let i = 0; i < this.props.boardSize; i  ) {
    newRow.push(this.intializeCell());
  }

  return newRow;
});

Why is this behavior happening? Is it because I'm initializing an Array of size 6 with blank Array objects? Or is it some weird behavior I'm not noticing going on in the for loop?

I will mention that when I alter the code to the following, it works as intended:

let cells = new Array(this.props.boardSize)
  .fill(new Array(this.props.boardSize).fill(0))
  .map((row) => {
    let newRow = row.map((_) => this.intializeCell());

    return newRow;
  });

CodePudding user response:

The problem is that .fill is using the same array object for each row. Therefore, when you update the row by updating e in the map function, you are always adding to the same array.

This would fix the problem.

let cells = new Array(this.props.boardSize).fill([]).map((e) => {
  let newRow = [];
  for (let i = 0; i < this.props.boardSize; i  ) {
    newRow.push(this.intializeCell());
  }

  return newRow;
});

.fill(value) fills the array with a copy of the same empty array N times. So by adding N items to the same array N times, you end up with N^2 items.

Another example

let test = new Array(3).fill([]);
test[0].push('a')
console.log(test)
// prints ['a','a','a']
  • Related