将数组拆分为块

新手上路,请多包涵

假设我有一个 Javascript 数组,如下所示:

["Element 1","Element 2","Element 3",...]; // with close to a hundred elements.

什么方法适合将数组分块(拆分)成许多较小的数组,比如说最多 10 个元素?

原文由 Industrial 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 739
2 个回答

array.slice() 方法可以根据需要从数组的开头、中间或结尾提取切片,而无需更改原始数组。

 const chunkSize = 10;
 for (let i = 0; i < array.length; i += chunkSize) {
 const chunk = array.slice(i, i + chunkSize);
 // do whatever
 }

最后一个 chunk 可能小于 chunkSize 。例如,当给定一个包含 12 个元素的 array 时,第一个块将有 10 个元素,第二个块只有 2 个。

请注意, chunkSize0 将导致无限循环。

原文由 Blazemonger 发布,翻译遵循 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 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题