Split an array into chunks in JavaScript
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:
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 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
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 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
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
let _ = require( "lodash" );
let arr = [1, 2, 3, 4, 5, 6,
"a" , "b" , "c" , "d" ];
console.log( "Before: " , arr)
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
Share your thoughts in the comments
Please Login to comment...