Lodash _.chunk() Method
Last Updated :
20 Oct, 2023
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
const _ = require( "lodash" );
let arr = [1, 2, 3, 4, 5, 6];
console.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
let _ = require( "lodash" );
let arr = [1, 2, 3, 4, 5, 6,
"a" , "b" , "c" , "d" ];
console.log( "Before: " , arr)
console.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
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 }
];
console.log( "Before: " , arr)
console.log( "After: " ,
lodash.chunk(arr, 1)[0]);
|
Output :
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...