Open In App

Underscore.js _.chunkAll() Method

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: 



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.




// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
  
// Array
var arr = [2, 2, 3, 5, 6]
  
// Number
var num = 3
  
// Making Chunked array
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 underscore contrib variable
var _ = require('underscore-contrib'); 
  
// Array
var arr = [2, 2, 3, 5, 6]
  
// Number
var num = 3
  
// Optional Arg
var opt = 4
  
// Making Chunked array
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 ] ]

Article Tags :