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: 

  • 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

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);

chevron_right


Output:

array  :
[ 2, 2, 3, 5, 6 ]
number :
3
chunked array :
[ [ 2, 2, 3 ], [ 6 ] ]

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.