How to split a JavaScript array into N arrays?

To split a JavaScript array into N arrays, we can use the splice method.

For instance, we write

const split = (array, n) => {
  const [...arr] = array;
  const res = [];
  while (arr.length) {
    res.push(arr.splice(0, n));
  }
  return res;
};

to define the split function.

In it, we make a copy of array with the rest operator.

And then we use a while loop that calls arr.splice to remove the items from index 0 to n - 1 from arr and return them in an array.

Then we call res.push to append the array into res.

This is done until arr is empty.