Horje
Split JavaScript Array in Chunks Using Lodash?

When working with arrays in JavaScript, you may encounter situations where you need to split an array into smaller chunks. This can be particularly useful when dealing with large datasets or when performing operations in a more manageable and efficient manner. The Lodash library provides a convenient method to achieve this. This article will guide you through the process of splitting a JavaScript array into chunks using Lodash.

Prerequisites

Approach

We have used Lodash’s chunk function to split an array into smaller chunks of a specified size (chunkSize). The _.chunk function divides the array into subarrays where each subarray contains elements as per the specified chunk size. For example, with chunkSize set to 3, the chunkedArray will contain arrays of [1, 2, 3], [4, 5, 6], [7, 8, 9], and [10]. This approach is useful for tasks like displaying data in paginated views or processing data in batches.

Install Lodash:

Open your terminal and navigate to your project directory. Run the following command to install Lodash:

npm install lodash

Dependencies:

 "dependencies": {
"lodash": "^4.17.21"
}

Example: This example shows the splitting array into chunks using Lodash.

JavaScript
// index.js
const _ = require('lodash');

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const chunkSize = 3;

const chunkedArray = _.chunk(array, chunkSize);
console.log(chunkedArray);

To start the application run the following command:

node index.js

Output:

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



Reffered: https://www.geeksforgeeks.org


JavaScript

Related
How to Find Property by Name in a Deep Object Using Lodash? How to Find Property by Name in a Deep Object Using Lodash?
How to Import a Single Lodash Function? How to Import a Single Lodash Function?
How to Remove First and Last Element from Array using JavaScript? How to Remove First and Last Element from Array using JavaScript?
How to Sort an Array Based on the Length of Each Element in JavaScript? How to Sort an Array Based on the Length of Each Element in JavaScript?
Data Analysis with JavaScript? Data Analysis with JavaScript?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
18