Open In App
Related Articles

Split an array into chunks in JavaScript

Improve Article
Improve
Save Article
Save
Like Article
Like

In this article, we have given a large array and we want to split it into chunks of smaller arrays in JavaScript. We have a few methods to do that such as:

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


Last Updated : 13 Jul, 2023
Like Article
Save Article
Similar Reads
Related Tutorials