How to Split Array into Chunks

This article is aimed at providing different methods of splitting an array into smaller chunks.

slice()

You can use a for loop to iterate through the array while repeatedly slicing chunks of the specified size using the slice() method. You can increase the iterator by the specified size on each iteration so as to start each new group after the previous one ended:

function chunkArray(array, size) {
  let result = []
  for (let i = 0; i < array.length; i += size) {
    let chunk = array.slice(i, i + size)
    result.push(chunk)
  }
  return result
}
let arr = ['a', 'b', 'c', 'd', 'e', 'f'];
let arrPairs = chunkArray(arr, 2);
console.log(arrPairs);

for...of

You can loop through the array using the for…of loop breaking it smaller chunks like this:

function chunkArray(array, size) {
  let result = []
  for (value of array) {
    let lastArray = result[result.length - 1]
    if (!lastArray || lastArray.length == size) {
      result.push([value])
    } else {
      lastArray.push(value)
    }
  }
  return result
}
var arr = ['a', 'b', 'c', 'd', 'e', 'f'];
var arrPairs = chunkArray(arr, 3);
console.log(arrPairs);

The if statement is used within the for...of loop for checking whether the result array is currently empty or the last chunk is complete. If it is complete, you can create a new group with the current value and push it into the result array. If it isn't complete, you can get the last array from the result and push the current value into it until the group is complete, in other words if the required size is reached.

splice()

You can use the splice() array method to extract elements of the specified size from the array that is received:

function chunkArray(array, size) {
  let result = []
  let arrayCopy = [...array]
  while (arrayCopy.length > 0) {
    result.push(arrayCopy.splice(0, size))
  }
  return result
}
var arr = ['a', 'b', 'c', 'd', 'e', 'f'];
var arrPairs = chunkArray(arr, 2);
console.log(arrPairs);

As the splice() element directly changes the received array, you should use the spread operator (…) to create a copy so that the operations do not affect the data that is received. Then each group created is added to the result by invoking the push() method.


Do you find this helpful?

Related articles