Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Split an array into chunks in JavaScript

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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:

Using 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




let i, j, chunk = 4;
let arr = [1, 2, 3, 4, 5, 6, 7, 8];
let arr1 = arr.slice(0, chunk);
let arr2 = arr.slice(chunk, chunk + arr.length);
 
console.log('Array1: ' + arr1 + '\nArray2: ' + arr2);


Output

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

Using 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




let i, j, chunk = 2;
let arr = [1, 2, 3, 4, 5, 6, 7, 8];
let arr1 = arr.splice(0, chunk);
let arr2 = arr.splice(0, chunk);
let arr3 = arr.splice(0, chunk);
let arr4 = arr.splice(0, chunk);
 
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
My Personal Notes arrow_drop_up
Last Updated : 05 Jun, 2023
Like Article
Save Article
Similar Reads
Related Tutorials