Lodash _.chunkAll() Method
Last Updated :
14 Sep, 2020
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.
Javascript
var _ = require( 'lodash-contrib' );
var arr = [2,2,3,5,6]
var num = 3
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.
Javascript
var _ = require( 'lodash-contrib' );
var arr = [2,2,3,5,6]
var num = 3
var opt = 4
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 ] ]
Share your thoughts in the comments
Please Login to comment...