Split an Array into Chunks in JavaScript
Last Updated :
11 Nov, 2024
Here are different methods to split an array into chunks in JavaScript.
1. Using slice() Method
The array slice() 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);
JavaScript
// Given array
let a = [ 10, 20, 30, 40, 50, 60, 70]
// Size of chunk
let chunk = 4;
// Spiltted arrays
let a1 = a.slice(0, chunk);
let a2 = a.slice(chunk, chunk + a.length);
// Display Output
console.log('Array 1: ' + a1 + '\nArray 2: ' + a2);
OutputArray 1: 10,20,30,40
Array 2: 50,60,70
2. Using splice() Method
The array splice() method is used to remove or replace existing elements and/or adding new elements.
Syntax
array.splice(index, number, item1, ....., itemN);
JavaScript
// Given array
let a = [10, 20, 30, 40, 50, 60, 70, 80];
// Size of chunk
let chunk = 2;
// Spliced arrays into 4 chunks
let a1 = a.splice(0, chunk);
let a2 = a.splice(0, chunk);
let a3 = a.splice(0, chunk);
let a4 = a.splice(0, chunk);
// Display Output
console.log('Array 1:', a1);
console.log('Array 2:', a2);
console.log('Array 3:', a3);
console.log('Array 4:', a4);
OutputArray 1: [ 10, 20 ]
Array 2: [ 30, 40 ]
Array 3: [ 50, 60 ]
Array 4: [ 70, 80 ]
3. Using Lodash _.chunk() Method
The Lodash _.chunk() method simplifies splitting an array into chunks by creating sub-arrays of a specified size. It automatically divides the array, returning an array of these chunks, with the last chunk containing the remaining elements if the array can’t be evenly split.
JavaScript
// Import lodash in the program
let _ = require('lodash');
// Given array
let a = [10, 20, 30, 40, 50, 60, 70, 80];
// Size of chunk
let chunkSize = 2;
// Use _.chunk() to split the array into chunks of size 2
let chunks = _.chunk(a, chunkSize);
// Display Output
console.log("Chunks:", chunks);
Output
Chunks: [[10, 20], [30, 40], [50, 60], [70, 80]]
4. Using JavaScript for Loop
The for loop is used to repeatedly execute some code to split the array into the chunks till the condition is true.
Syntax
for( initialization ; condition ; increment ){
// Code to be executed
}
JavaScript
// Given array
let a = [10, 20, 30, 40, 50, 60, 70, 80];
// Size of chunk
let chunkSize = 2;
// Initialize the output array
let chunks = [];
// Loop to split array into chunks
for (let i = 0; i < a.length; i += chunkSize) {
let chunk = [];
// Iterate for the size of chunk
for (let j = i; j < i + chunkSize && j < a.length; j++) {
chunk.push(a[j]);
}
// push the chunk to output array
chunks.push(chunk);
}
// Display Output
console.log("Chunks:", chunks);
OutputChunks: [ [ 10, 20 ], [ 30, 40 ], [ 50, 60 ], [ 70, 80 ] ]
5. Using reduce() with slice() Method
The array reduce() method is used to iterate over the array and perform some operations to split the array into chunks.
Syntax
array.reduce(
function(total, currentValue, currentIndex, arr),
initialValue
)
JavaScript
// Given array
let a = [10, 20, 30, 40, 50, 60, 70, 80];
// Size of chunk
let chunkSize = 2;
// Split the array into chunks using reduce
let chunks = a.reduce((acc, _, index) => {
// Create chunk using array.slice()
// and push into the accumulator
acc.push(a.slice(index, index + chunkSize));
return acc;
}, []);
// Display Output
console.log("Chunks:", chunks);
OutputChunks: [
[ 10, 20 ], [ 20, 30 ],
[ 30, 40 ], [ 40, 50 ],
[ 50, 60 ], [ 60, 70 ],
[ 70, 80 ], [ 80 ]
]
Similar Reads
How to Add Elements to a JavaScript Array?
Here are different ways to add elements to an array in JavaScript. 1. Using push() MethodThe push() method adds one or more elements to the end of an array and returns the new length of the array. Syntax array.push( element1, element2, . . ., elementN );[GFGTABS] JavaScript const arr = [10, 20, 30,
3 min read
Create an Array of Given Size in JavaScript
The basic method to create an array is by using the Array constructor. We can initialize an array of certain length just by passing a single integer argument to the JavaScript array constructor. This will create an array of the given size with undefined values. Syntax cosnt arr = new Array( length )
4 min read
Insert at the Beginning of an Array in JavaScript
Following are different ways to add new elements at the beginning of an array 1. Using the Array unshift() Method - Most Used:Adding new elements at the beginning of the existing array can be done by using the Array unshift() method. This method is similar to the push() method but it adds an element
2 min read
Remove Elements From a JavaScript Array
Here are the various methods to remove elements from a JavaScript Array 1. Using pop() methodThe pop() method removes and returns the last element of an array. This function decreases the length of the array by 1 every time the element is removed. [GFGTABS] javascript let a = ["Apple",
6 min read
Remove Duplicate Elements from JavaScript Array
To Remove the elements from an array we can use the JavaScript set method. Removing duplicate elements requires checking if the element is present more than one time in the array. 1. Using JavaScript Set() - Mostly UsedThe JavaScript Set() method creates an object containing only unique values. To r
3 min read
How to Remove Multiple Elements from Array in JavaScript?
Here are various methods to remove multiple elements from an array in JavaScript 1. Using filter() MethodThe filter() method creates a new array with the elements that pass the condition. This method does not change the original array. [GFGTABS] JavaScript let a = [1, 2, 3, 4, 5]; let remove = [2, 4
4 min read
Insert at the Beginning of an Array in JavaScript
Following are different ways to add new elements at the beginning of an array 1. Using the Array unshift() Method - Most Used:Adding new elements at the beginning of the existing array can be done by using the Array unshift() method. This method is similar to the push() method but it adds an element
2 min read
Reverse an Array in JavaScript
Here are the different methods to reverse an array in JavaScript 1. Using the reverse() MethodJavaScript provides a built-in array method called reverse() that reverses the elements of the array in place. This method mutates the original array and returns the reversed array. [GFGTABS] JavaScript let
3 min read
JavaScript - Delete last Occurrence from JS Array
These are the following ways to remove the last Item from the given array: 1. Using pop() Method (Simple and Easiest Method for Any Array) The pop() method is used to get the last element of the given array it can also be used to remove the last element from the given array. [GFGTABS] JavaScript let
2 min read
Remove Empty Elements from an Array in JavaScript
Here are different approaches to remove empty elements from an Array in JavaScript. 1. Using array.filter() MethodThe array filter() method is used to create a new array from a given array consisting of elements that satisfy given conditions. array.filter( callback( element, index, arr ), thisValue
3 min read