使用 Lodash 将 JavaScript 数组拆分为块
我需要将 JavaScript 数组拆分为 n 大小的块。
例如:给定这个数组
["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10", "a11", "a12", "a13"]
并且 n
等于 4,输出应该是这样的:
[ ["a1", "a2", "a3", "a4"],
["a5", "a6", "a7", "a8"],
["a9", "a10", "a11", "a12"],
["a13"]
]
我知道纯 JavaScript 这个问题的解决方案,但由于我已经在使用 Lodash 我想知道是否洛达什为此提供了更好的解决方案。
编辑:
我创建了一个 jsPerf 测试来检查下划线解决方案慢了多少。
I need to split a JavaScript array into n
sized chunks.
E.g.: Given this array
["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10", "a11", "a12", "a13"]
and a n
equals to 4, the output should be this:
[ ["a1", "a2", "a3", "a4"],
["a5", "a6", "a7", "a8"],
["a9", "a10", "a11", "a12"],
["a13"]
]
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.
Edit:
I created a jsPerf test to check how much slower the underscore solution is.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
看一下 lodash 的块:https://lodash.com/docs#chunk< /a>
Take a look at lodash' chunk: https://lodash.com/docs#chunk
对于基于下划线的解决方案,请尝试以下操作:
使用链包装器方法,您可以将两个语句组合在一起,如下所示:
For Underscore based solution try this:
Using the chain wrapper method you can combine the two statements as below:
从 1.9.0 版本开始,Underscore 原生支持 _.chunk()。
Underscore supports _.chunk() natively as of version 1.9.0.
一个可能更简单的表达:
A possibly simpler expression:
尝试这个,它更实用(例如,如果您想根据每个子数组中要容器的项目数量来拆分数组):
以及您的情况下的使用:
和另一种情况:
try this one it is much more practical (for example, if you would want to split the array based on amount of items to be container in each sub array):
and the use in your case:
and another case: