Splitting an array into chunks in JavaScript


In this article the given task is to split array elements into n sized chunks in JavaScript. We have some approaches to perform the splitting operation on array, those will be discussed below.

Let’s assume some simple input and output scenarios 

Assume there is an array containing elements in it. Example, array = [10, 20, 30, 40] and let’s take the chunk size as 2.

Input = [10, 20, 30, 40]
Ouput = [[10, 20], [30, 40]]

The elements will be divided into two chunks, the first argument specifies the starting index and the second argument specifies the ending index.

Let’s look into these two approaches below 

  • Using the slice method and for loop.

  • Using the splice method and while loop.

Using Slice() method

The slice() method in JavaScript returns a shallow copy of a part of an array into a new object array. The slice() method is the easiest method to extract a chunk of an array or slice the array.

Syntax

Following is the syntax of the slice() method in JavaScript –

slice(start, end)

This returns the part of the invoked array between the start and end.

Example: Slice with for loop

In the example below, the for loop is used with the slice method to split the array elements into chunks. We broke the array into chunk sizes of 2 by iterating through the array.

function array_into_chunks (array, size_of_chunk) {
   const arr = [];
   for (let i = 0; i < array.length; i += size_of_chunk) {
      const chunk = array.slice(i, i + size_of_chunk);
      arr.push(chunk);
   }
   return arr;
}
const array = [1, 6, 7, 3, 5, 9, 4];
console.log(array_into_chunks(array, 2));

Example: Splice method with a while loop

In the below example, we have used a while loop to traverse the array. we perform the splicing operation in each and every iteration and push each chunk into the new array unless there are no more elements left in the original array that is array.length is greater than 0.

function array_into_chunks (array, chunkSize) {
   const arr = [];
   while (array.length > 0) {
      const chunk = array.splice(0, chunkSize);
      arr.push(chunk);
   }
   return arr;
}
const array = [1, 6, 7, 3, 5, 9, 4];
console.log(array_into_chunks (array, 2));

Note

The splice() method will change the original array. But in the case of the slice() method, it creates a copy of the original array. Hence there won’t be any modification in the original array.

Example 2: Array map in the prototype of the array

Every element in an array is called by the map function once, sequentially, and it creates a new array from the results. The function will output an array whose length is determined by dividing the length of the input array by the chunk size. The array will first be filled with undefined by the fill function (because no parameters are provided), and then every undefined value will be replaced by a new array (the result of slicing the provided array with the proper index).

In the example below, we have defined the chunk method in the prototype of the array that will return an array with chunk arrays of a given size.

Object.defineProperty(Array.prototype, 'chunk', {
   value: function(size_of_chunk) {
      var that = this;
      return Array(Math.ceil(that.length/size_of_chunk)).fill().map(function(_,i){
         return that.slice(i*size_of_chunk, i*size_of_chunk + size_of_chunk); 
      });
    }
});
var arr = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120].chunk(4);
console.log(arr);

Updated on: 19-Dec-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements