Last Updated : 30 Aug, 2024
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:
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 script
const _ = require("lodash");
let arr = [1, 2, 3, 4, 5, 6];
// Making chunks of size 1
console.log(_.chunk(arr, 1))
Output:
OUTPUT EXAMPLE 1Example 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 script
let _ = require("lodash");
let arr = [1, 2, 3, 4, 5, 6,
"a", "b", "c", "d"];
console.log("Before: ", arr)
// Making chunks of size 3
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
// 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 chunks
console.log("Before: ", arr)
// Printing the first element
// of the chunk as size 1
console.log("After: ",
lodash.chunk(arr, 1)[0]);
Output :
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4