Open In App

Split an array into chunks in JavaScript

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

In this article, we have given a large array and we want to split it into chunks of smaller arrays in JavaScript.

Methods to split array into chunks:

Method 1: Using JavaScript slice() method

This method returns a new array containing the selected elements. This method selects the elements starting from the given start argument and ends at, but excluding the given end argument. 

Syntax:

array.slice(start, end);

Example: This example uses the slice() method to split the array into chunks of the array. This method can be used repeatedly to split an array of any size. 

Javascript




// Size of chunk
let chunk = 4;
 
// Input array
let arr = [1, 2, 3, 4, 5, 6, 7, 8];
 
// Spiltted arrays
let arr1 = arr.slice(0, chunk);
let arr2 = arr.slice(chunk, chunk + arr.length);
 
// Display Output
console.log('Array1: ' + arr1 + '\nArray2: ' + arr2);


Output

Array1: 1,2,3,4
Array2: 5,6,7,8

Method 2: Using JavaScript splice() method

This method adds/removes items to/from an array, and returns the list of removed item(s). 

Syntax:

array.splice(index, number, item1, ....., itemN);

Example: This example uses the splice() method to split the array into chunks of the array. This method removes the items from the original array. This method can be used repeatedly to split an array of any size. 

Javascript




// Size of aaray chunks
let chunk = 2;
 
// Input array
let arr = [1, 2, 3, 4, 5, 6, 7, 8];
 
// Splitted arrays
let arr1 = arr.splice(0, chunk);
let arr2 = arr.splice(0, chunk);
let arr3 = arr.splice(0, chunk);
let arr4 = arr.splice(0, chunk);
 
// Display output
console.log("Array1: " + arr1);
console.log("Array2: " + arr2);
console.log("Array3: " + arr3);
console.log("Array4: " + arr4);


Output

Array1: 1,2
Array2: 3,4
Array3: 5,6
Array4: 7,8

Method 3: Using Lodash _.chunk() Method

In this approach, we are using Lodash _.chunk() method that returns the given array in chunks according to the given value.

Example: In this example, we are breaking the array by passing size ‘3’ into the _.chunk() method. The size of chunk can be varied and array of different data type can be used with chunk function.

Javascript




// Requiring the lodash module
// in the script
let _ = require("lodash");
let arr = [1, 2, 3, 4, 5, 6,
    "a", "b", "c", "d"];
console.log("Before: ", arr)
 
// Making chunks of size 3
console.log("After: ", _.chunk(arr, 3))


Output:

Before:  [
1, 2, 3, 4, 5,
6, 'a', 'b', 'c', 'd'
]
After: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 'a', 'b', 'c' ], [ 'd' ] ]


Last Updated : 18 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads