1

How can I split an array into equal sized arrays:

var a = [1,2,3,4,5,6,7,8];
var b = a.split(2);
// b is equal to [[1,2],[3,4],[5,6],[7,8]];
// one possible way might be something like
[0,1,2,3].map(_ => a.slice(_* 2, _+2));
eguneys
  • 6,028
  • 7
  • 31
  • 63
  • https://stackoverflow.com/questions/8495687/split-array-into-chunks – epascarello Jun 25 '19 at 20:15
  • There is a discussion here: [https://stackoverflow.com/questions/9181188/splice-an-array-in-half-no-matter-the-size]. Kind of interesting what to do if the array has an odd number of elements. – SScotti Jun 25 '19 at 20:15

2 Answers2

1

const chunk = (arr, size) => arr.reduce((carry, _, index, orig) => !(index % size) ? carry.concat([orig.slice(index,index+size)]) : carry, []);

console.log(chunk([1,2,3,4,5,6,7,8], 2))
dave
  • 62,300
  • 5
  • 72
  • 93
1

For the second index for splicing, you need to add one and multiply with the length of the inner arrays.

var a = [1, 2, 3, 4, 5, 6, 7, 8],
    b = [0, 1, 2, 3].map(i => a.slice(i * 2, (i + 1) * 2));

console.log(b);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392