Collect.js | chunk() Function
The chunk() function breaks the collection to many small collections of the given size. In JavaScript, the array is first converted to a collection and then the function is applied to the collection.
Syntax:
data.chunk(x)
Parameter: This function accepts a single parameter as mentioned above and described below.
- x : This parameter holds an integer number that defines where to break the collection
Return value: Return the sub collection of the main collection
Below examples illustrate the chunk() function in collect.js:
Example 1: Here in this example, we take a collection and then using the chunk() function we divide the collection.
Javascript
// It is used to import collect.js library const collect = require( 'collect.js' ); const collection = collect([1, 2, 3, 4, 5, 6, 7]); const x = collection.chunk(5); console.log(x.all()); |
Output :
[ Collection { items: [ 1, 2, 3, 4, 5 ] }, Collection { items: [ 6, 7 ] } ]
Example 2: In this example, we will pass two values in the chunk() function.
Javascript
// It is used to import collect.js library const collect = require( 'collect.js' ); const collection = collect([0 , 1 , 2 , 3 , 4 , 5 , 6 ]); const x = collection.chunk(2, 4); console.log(x.all()); |
Output:
[ Collection { items: [ 0, 1 ] }, Collection { items: [ 2, 3 ] }, Collection { items: [ 4, 5 ] }, Collection { items: [ 6 ] } ]
Contact Us