How to split an array into chunks in JavaScript

Published on

Sometimes you want to split an array into equal chunks. Maybe you're writing software for a dog rescue centre that is packed to the rafters with love hungry pups and now has to divide eligible dogs into pairs in order to have space for more. Or it could be that you just need to split an array for some less convoluted reason but we'll use the rescue centre as an example here. The easiest way to achieve this is using Array.prototype.slice() combined with a for loop.

const sizeOfChunk = 2;
const dogs = ['Biscuit', 'Max', 'Cooper', 'Bailey', 'Coco', 'Roxy'];

let chunkedDogs = [];

for (let i = 0; i < dogs.length; i += sizeOfChunk) {
  chunkedDogs.push(dogs.slice(i, i + sizeOfChunk));
}

console.log(chunkedDogs);

// [['Biscuit', 'Max'], ['Cooper', 'Bailey'], ['Coco', 'Roxy']]

We're using slice in the above example to actually divide the original array by the size of the chunk, working our way further along the array each time we cycle through the loop. If the number of items in the array is not divisible by your chosen chunk size then the final chunk will contain the remainder. Although the above example is the simplest answer to this question if you wanted to take a more functional approach you can use the following.

const sizeOfChunk = 2;
const dogs = ['Biscuit', 'Max', 'Cooper', 'Bailey', 'Coco', 'Roxy'];

console.log(chunkedDogs);

// [['Biscuit', 'Max'], ['Cooper', 'Bailey'], ['Coco', 'Roxy']]

If you're using lodash or underscore you can use their chunk function to achieve this same result.

const sizeOfChunk = 2;
const dogs = ['Biscuit', 'Max', 'Cooper', 'Bailey', 'Coco', 'Roxy'];

const chunkedDogs = _.chunk(dogs, sizeOfChunk);

console.log(chunkedDogs);

// [['Biscuit', 'Max'], ['Cooper', 'Bailey'], ['Coco', 'Roxy']]