TypeOfNaN

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

Nick Scialli
January 24, 2021

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
  .fill('')
  // 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)
    .fill('')
    .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 senior UI engineer at Microsoft.

© 2024 Nick Scialli