Lodash _.chunk() function is used to break the array into small chunks. Each chunk is an array of sizes as given.
Syntax:
_.chunk(array, size);
Parameters:
- array: An array to be processed by chunk function.
- size: This describes the size of the chunk.
Return Value:
It returns the array of chunks that is also an array.
Example 1: In this example, we are breaking the array by passing size ‘1’ into the _.chunk() method.
Javascript
// Requiring the lodash module// in the scriptconst _ = require("lodash");let arr = [1, 2, 3, 4, 5, 6];Â
// Making chunks of size 1console.log(_.chunk(arr, 1)) |
Output:Â
OUTPUT EXAMPLE 1
Example 2: In this example, we are breaking the array by passing size ‘3’ into the _.chunk() method. The size of chunk can be varied and array of different data type can be used with chunk function.
Javascript
// Requiring the lodash module// in the scriptlet _ = require("lodash");let arr = [1, 2, 3, 4, 5, 6,    "a", "b", "c", "d"];console.log("Before: ", arr)Â
// Making chunks of size 3console.log("After: ", _.chunk(arr, 3)) |
Output:Â
Example 3: In this example, we are breaking the 2d array by passing size ‘2’ into the _.chunk() method. Using array of array with chunk.
Javascript
// Requiring the lodash module // in the script.let lodash = require("lodash");let arr = [    [1, 2, 3],    [4, 5, 6, 7, 8],    [9, 10, 1, 2]];Â
console.log("Before: ", arr)console.log("After: ", lodash.chunk(arr, 2)) |
Output:Â
Example 4: In this example, we are breaking the array of object by passing size ‘1’ into the _.chunk() method.
Javascript
let lodash = require("lodash");let arr = [    { "a": 1, "b": 2, "c": 3 },    { "d": 1, "e": 2, "f": 3 },    { "d": 1, "e": 2, "f": 3 }];Â
// Array before breaking in to chunksconsole.log("Before: ", arr)Â
// Printing the first element // of the chunk as size 1console.log("After: ",    lodash.chunk(arr, 1)[0]); |
Output :
