Open In App

Underscore.js _.chunkAll() Method

Last Updated : 29 Jul, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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




// 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.

Javascript




// 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 ] ]


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads