Underscore.js _.chunkAll() Method
Last Updated :
29 Jul, 2020
The _.chunkAll() Method is similar to _.chunk() method except for the following that, _.chunkAll() method will never drop short chunks from the end. It also takes an array and a number to make chunks and chunked array.
syntax:
_.chunkAll(array, number);
or
_.chunkAll(array, number, partitions);
Parameters:
- array: The array to be split.
- number: The size of the chunks to be formed.
- partitions (optional): It signifies how partitions should be built from skipped regions.
Return Value: This method returns a chunked array.
Note: This will not work in normal JavaScript because it requires the underscore.js contrib library to be installed. Underscore.js contrib library can be installed using npm install underscore-contrib –save
Example 1: In this example, we will chunk a simple array.
Javascript
var _ = require( 'underscore-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( 'underscore-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...