假设我有一个 Javascript 数组,如下所示:
["Element 1","Element 2","Element 3",...]; // with close to a hundred elements.
什么方法适合将数组分块(拆分)成许多较小的数组,比如说最多 10 个元素?
原文由 Industrial 发布,翻译遵循 CC BY-SA 4.0 许可协议
假设我有一个 Javascript 数组,如下所示:
["Element 1","Element 2","Element 3",...]; // with close to a hundred elements.
什么方法适合将数组分块(拆分)成许多较小的数组,比如说最多 10 个元素?
原文由 Industrial 发布,翻译遵循 CC BY-SA 4.0 许可协议
这是一个使用 reduce 的 ES6 版本
const perChunk = 2 // items per chunk
const inputArray = ['a','b','c','d','e']
const result = inputArray.reduce((resultArray, item, index) => {
const chunkIndex = Math.floor(index/perChunk)
if(!resultArray[chunkIndex]) {
resultArray[chunkIndex] = [] // start a new chunk
}
resultArray[chunkIndex].push(item)
return resultArray
}, [])
console.log(result); // result: [['a','b'], ['c','d'], ['e']]
并且您已准备好链接进一步的映射/减少转换。您的输入数组保持不变
如果您更喜欢较短但可读性较差的版本,则可以将一些 concat
添加到混合中以获得相同的最终结果:
inputArray.reduce((all,one,i) => {
const ch = Math.floor(i/perChunk);
all[ch] = [].concat((all[ch]||[]),one);
return all
}, [])
您可以使用余数运算符将连续的项目放入不同的块中:
const ch = (i % perChunk);
原文由 Andrei R 发布,翻译遵循 CC BY-SA 4.0 许可协议
10 回答11.1k 阅读
6 回答3k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
2 回答2.7k 阅读✓ 已解决
3 回答2.3k 阅读✓ 已解决
3 回答2.1k 阅读✓ 已解决
array.slice()
方法可以根据需要从数组的开头、中间或结尾提取切片,而无需更改原始数组。最后一个
chunk
可能小于chunkSize
。例如,当给定一个包含 12 个元素的array
时,第一个块将有 10 个元素,第二个块只有 2 个。请注意,
chunkSize
为0
将导致无限循环。