How to use Array.reduce() In Javascript
Using Array.reduce(), split an array into chunks of a specified size. The reduce function accumulates chunks based on the chunkSize, pushing sliced portions of the array into the chunks array, and returns the resulting array of chunks.
Example: In this example we splits an array into chunks of a specified size using the reduce method. It iterates through the array, pushing subarrays of the defined chunk size into a resulting array.
// Size of chunk
let chunk = 4;
// Input array
let arr = [1, 2, 3, 4, 5, 6, 7, 8];
// Split array into chunks using reduce method
let splittedArrays = arr.reduce((result, item, index) => {
if (index % chunk === 0) {
result.push(arr.slice(index, index + chunk));
}
return result;
}, []);
// Display Output
splittedArrays.forEach((subArray, index) => {
console.log(`Array${index + 1}: ${subArray}`);
});
Output
Array1: 1,2,3,4 Array2: 5,6,7,8
Split an array into chunks in JavaScript
Splitting an array into chunks in JavaScript involves dividing the array into smaller arrays of a specified size. This process is useful for managing large datasets more efficiently or for processing data in smaller, more manageable portions within the application.
Methods to split the array into chunks:
Table of Content
- Using JavaScript slice() method
- Using JavaScript splice() method
- Using Lodash _.chunk() Method
- Using a Loop to Split the Array
- Using Array.reduce():
- Using Array.from() and Array.splice()