How to Split an Array Into a Group of Arrays in JavaScript

Nick Scialli January 24, 2021🚀 1 minute read

If you're enjoying this blog, please consider:

Sometimes we have one array that we might want to split into multiple arrays. Here’s a quick and easy way to do that.

The Problem

Let’s say we have the following array:

const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];

And, for whatever reason, we need to split this into an array of three subarrays like this:

const result = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],

How can we do this?

A Quick Solution

One quick solution would be as follows. Importantly, this creates a new results array and doesn’t mutate the nums array.

const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];

// Get number of elements per subarray
const numsPerGroup = Math.ceil(nums.length / 3);
// Create array based on number of groups
const result = new Array(3)
  // Make sure each element isn't empty
  // For each group, grab the right `slice` of the input array
  .map((_, i) => nums.slice(i * numsPerGroup, (i + 1) * numsPerGroup));

And this works! Whenever I come up with a tidy solution like this, however, I like to see if I can abstract it into a reusable function.

A Reusable createGroups Function

To make this reusable, we just need to put the code in a function and replace the number 3 and the nums array with user-provided arguments:

function createGroups(arr, numGroups) {
  const perGroup = Math.ceil(arr.length / numGroups);
  return new Array(numGroups)
    .map((_, i) => arr.slice(i * perGroup, (i + 1) * perGroup));

And it should be that simple! Let’s see it in action.

console.log(createGroups(['cat', 'dog', 'pig', 'frog'], 2));
// [["cat", "dog"], ["pig", "frog"]]

console.log(createGroups([1, 2, 3, 4, 5], 3));
// [[1, 2], [3, 4], [5]]

It works great!

Nick Scialli

Nick Scialli is a software engineer at the U.S. Digital Service.

Subscribe to the mailing list!

If you like what I post here, please sign up to get updates and code insights in your inbox. I won't spam you and you can unsubscribe any time!

Powered by Buttondown.