![]() |
VOOZH | about |
Here are different methods to split an array into chunks in JavaScript.
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);Array 1: 10,20,30,40 Array 2: 50,60,70
The array splice() method is used to remove or replace existing elements and/or adding new elements.
Syntax
array.splice(index, number, item1, ....., itemN);Array 1: [ 10, 20 ] Array 2: [ 30, 40 ] Array 3: [ 50, 60 ] Array 4: [ 70, 80 ]
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.
Output
Chunks: [[10, 20], [30, 40], [50, 60], [70, 80]]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
}
Chunks: [ [ 10, 20 ], [ 30, 40 ], [ 50, 60 ], [ 70, 80 ] ]
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
)
Chunks: [ [ 10, 20 ], [ 20, 30 ], [ 30, 40 ], [ 40, 50 ], [ 50, 60 ], [ 60, 70 ], [ 70, 80 ], [ 80 ] ]