0

I have the following code, console.log is just to show what happens

function splitToChunks(array, parts) {
  let result = new Array(parts).fill([]);
  array.map((e,i)=> {console.log("r[",i%parts,"] gets -> ", e )|| result[i%parts].push(e)})
  return result;
}

testing with arr = [0...11]

result

expected result would be:

 [
  [0, 4, 8],
  [1, 5, 9],
  [2, 6, 10],
  [3, 7, 11],
 ]
Diego Vallejo
  • 55
  • 1
  • 7

1 Answers1

1

The issue here is that the fill() array method passes by reference, not value, so it's actually the exact same "deep" object being passed to each sub-array, not new ones each time.

A quick workaround for this is to use fill() first and then map() the new array:

function splitToChunks(array, parts) {
  let result = Array(parts).fill().map(e => []);
  array.map((e,i) => { result[i % parts].push(e) });
  return result;
}
Brandon McConnell
  • 5,776
  • 1
  • 20
  • 36