0

When I try to iterate over an array and assign each element to its appropriate position in a matrix, the entire column is being updated instead of only the specific data point I am trying to modify.

I expected

[ [ 'a', 'b' ], [ 'c', 'd' ], [ 'e' ] ]

But instead got

[ [ 'e', 'd' ], [ 'e', 'd' ], [ 'e', 'd' ] ]

function chunkArrayInGroups(arr, size) {
  const matrix = new Array(Math.ceil(arr.length / size)).fill([])
  for (let i = 0; i < arr.length; i++) {
    let row = Math.floor(i / size)
    let col = i % size
    console.log(`matrix[${row}][${col}]`)
    matrix[row][col] = arr[i]
  }
  console.log(matrix)
  return matrix
}
console.log(
  chunkArrayInGroups(["a","b","c","d","e"],2)
)
mplungjan
  • 169,008
  • 28
  • 173
  • 236

0 Answers0