使用 Lodash 分块分割 JavaScript 数组 [英] Split JavaScript array in chunks using Lodash
本文介绍了使用 Lodash 分块分割 JavaScript 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要将 JavaScript 数组拆分为 n
个大小的块.
I need to split a JavaScript array into n
sized chunks.
例如:给定这个数组
["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10", "a11", "a12", "a13"]
并且一个 n
等于 4,输出应该是这样的:
and a n
equals to 4, the output should be this:
[ ["a1", "a2", "a3", "a4"],
["a5", "a6", "a7", "a8"],
["a9", "a10", "a11", "a12"],
["a13"]
]
我知道针对此问题的纯 JavaScript 解决方案,但由于我已经在使用 Lodash 我想知道 Lodash 是否为此提供了更好的解决方案.
I aware of pure JavaScript solutions for this problem, but since I am already using Lodash I am wondering if Lodash provides a better solution for this.
我创建了一个 jsPerf 测试来检查下划线解决方案的速度有多慢.
I created a jsPerf test to check how much slower the underscore solution is.
推荐答案
看看 lodash' chunk: https://lodash.com/docs#chunk
Take a look at lodash' chunk: https://lodash.com/docs#chunk
const data = ["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10", "a11", "a12", "a13"];
const chunks = _.chunk(data, 3);
console.log(chunks);
// [
// ["a1", "a2", "a3"],
// ["a4", "a5", "a6"],
// ["a7", "a8", "a9"],
// ["a10", "a11", "a12"],
// ["a13"]
// ]
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
这篇关于使用 Lodash 分块分割 JavaScript 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文