本文介绍了使用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数组拆分为多个块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!