Open In App

Split an Array into Chunks in JavaScript

Last Updated : 11 Nov, 2024
Comments
Improve
Suggest changes
2 Likes
Like
Report

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);

Output
Array 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);

Output
Array 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.

// 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
}

Output
Chunks: [ [ 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
)

Output
Chunks: [
  [ 10, 20 ], [ 20, 30 ],
  [ 30, 40 ], [ 40, 50 ],
  [ 50, 60 ], [ 60, 70 ],
  [ 70, 80 ], [ 80 ]
]

Similar Reads