Lodash _.chunk() 方法
Lodash 是一个基于 underscore.js 的 JavaScript 库。 Lodash 有助于处理数组、字符串、对象、数字等。 Loadsh.chunk()函数用于将数组分成小块。每个块都是给定大小的数组。
句法:
chunk(array, size)
参数:该函数接受上面提到的两个参数,如下所述。
- 数组:要被块函数处理的数组。
- size:这描述了块的大小。
返回值:它返回也是一个数组的块数组
注意:在使用下面给出的代码之前,请使用命令npm install lodash
安装 lodash 模块。
示例 1:
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))
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))
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))
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]);
输出:
示例 2: chunk 的大小可以变化,不同数据类型的数组可以与 chunk函数一起使用。
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))
输出:
示例 3:使用带有块的数组数组。
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))
输出:
示例 4:使用带有块的对象数组。
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]);
输出 :