Categories
JavaScript Answers

How to split a JavaScript array into N arrays?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *