Open In App

How to Split JavaScript Array in Chunks using Lodash?

Splitting a JavaScript array into chunks consists of dividing the array into smaller subarrays based on a specified size or condition. In this article, we will explore different approaches to splitting JavaScript array into chunks using Lodash.

Below are the approaches to Split JavaScript array in chunks using Lodash:

Using Lodash _.chunk() Method

In this approach, we are using the _.chunk method from Lodash to split the array into chunks of size 3, and then we log the resulting array res to the console.

Syntax:

_.chunk(array, size);

Example: The below example uses _.chunk() Method to Split the JavaScript array into chunks using Lodash.

const _ = require('lodash');
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const res = _.chunk(array, 3);
console.log(res);

Output

[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ], [ 10 ] ]

Using Lodash _.reduce() Method

In this approach, we are using _.reduce from Lodash to iterate over the array and accumulate chunks of size chunkSize by pushing elements into subarrays. Finally, we log the resulting chunked array res to the console.

Syntax:

_.reduce(collection, iteratee, accumulator)

Example: The below example uses the _.reduce() Method to Split the JavaScript array into chunks using Lodash.

const _ = require('lodash');
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const chunkSize = 3;
const res = _.reduce(array, (result, value, index) => {
    if (index % chunkSize === 0) {
        result.push([]);
    }
    result[Math.floor(index / chunkSize)].push(value);
    return result;
}, []);
console.log(res);

Output

[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ], [ 10 ] ]
Article Tags :