Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.
The _.chunkAll() Method is used to break the given array in to small chunks of the given size. It is similar to the _.chunk() method except that this method will never drop short chunks from the end.
Syntax:
_.chunkAll( array, number )
or
_.chunkAll( array, number, partitions )
Parameters: This method takes three parameters as mentioned above and discussed below:
- array: It is the array that has to be split.
- number: It is the size of the chunks to be formed.
- partitions: It specifies how partitions should be built from skipped regions. It is an optional parameter.
Return Value: This method returns a chunked array.
Note: This will not work in normal JavaScript because it requires the lodash-contrib library to be installed. The lodash-contrib library can be installed using npm install lodash-contrib –save
Example 1: In this example, we will chunk a simple array.
// Defining lodash contrib variable var _ = require( 'lodash-contrib' );
// Array to be chunked var arr = [2,2,3,5,6]
// Number that denotes the size // of the chunks var num = 3
// Using the _.chunkAll() method var carr = _.chunkAll(arr, num);
console.log( "array : " );
console.log(arr); console.log( "number : " );
console.log(num); console.log( "chunked array : " );
console.log(carr); |
Output:
array : [ 2, 2, 3, 5, 6 ] number : 3 chunked array : [ [ 2, 2, 3 ], [ 5, 6 ] ]
Example 2: In this example, we will use the optional argument to build skipped partitions.
// Defining lodash contrib variable var _ = require( 'lodash-contrib' );
// Array to be chunked var arr = [2,2,3,5,6]
// Number that denotes the size // of the chunks var num = 3
// Optional Arg var opt = 4
// Using the _.chunkAll() method carr = _.chunkAll(arr, num, opt); console.log( "array : " );
console.log(arr); console.log( "number : " );
console.log(num); console.log( "chunked array : " );
console.log(carr); |
Output:
array : [ 2, 2, 3, 5, 6 ] number : 3 chunked array : [ [ 2, 2, 3 ], [ 6 ] ]