让我们说我有一个Javascript数组看起来如下:

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

什么样的方法适合将数组分成许多更小的数组,假设最多有10个元素?


当前回答

下面的ES2015方法不需要定义函数,直接在匿名数组上工作(例如块大小为2):

[11,22,33,44,55].map((_, i, all) => all.slice(2*i, 2*i+2)).filter(x=>x.length)

如果你想为此定义一个函数,你可以这样做(改进K._对Blazemonger的回答的评论):

const array_chunks = (array, chunk_size) => array
    .map((_, i, all) => all.slice(i*chunk_size, (i+1)*chunk_size))
    .filter(x => x.length)

其他回答

我只是在groupBy函数的帮助下写了这个。

// utils const group = (source) => ({ by: (grouping) => { const groups = source.reduce((accumulator, item) => { const name = JSON.stringify(grouping(item)); accumulator[name] = accumulator[name] || []; accumulator[name].push(item); return accumulator; }, {}); return Object.keys(groups).map(key => groups[key]); } }); const chunk = (source, size) => group(source.map((item, index) => ({ item, index }))) .by(x => Math.floor(x.index / size)) .map(x => x.map(v => v.item)); // 103 items const arr = [6,2,6,6,0,7,4,9,3,1,9,6,1,2,7,8,3,3,4,6,8,7,6,9,3,6,3,5,0,9,3,7,0,4,1,9,7,5,7,4,3,4,8,9,0,5,1,0,0,8,0,5,8,3,2,5,6,9,0,0,1,5,1,7,0,6,1,6,8,4,9,8,9,1,6,5,4,9,1,6,6,1,8,3,5,5,7,0,8,3,1,7,1,1,7,6,4,9,7,0,5,1,0]; const chunks = chunk(arr, 10); console.log(JSON.stringify(chunks));

js

函数splitToBulks(arr, bulkSize = 20) { Const bulks = []; 对于(设I = 0;i < Math.ceil(arr。长度/ bulkSize);我+ +){ bulks.push(加勒比海盗。(i * bulkSize, (i + 1) * bulkSize)); } 返回散货; } console.log(splitToBulks([1,2,3,4,5,6,7], 3));

打印稿

function splitToBulks<T>(arr: T[], bulkSize: number = 20): T[][] {
    const bulks: T[][] = [];
    for (let i = 0; i < Math.ceil(arr.length / bulkSize); i++) {
        bulks.push(arr.slice(i * bulkSize, (i + 1) * bulkSize));
    }
    return bulks;
}

整洁干净,易于理解

 let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];
 let len = nums.length ;

    const chunkArr = (arr, chunkNo) => {
      let newArr = [];
      for(let i = 0; i < len; i++){
        if(nums[0] !== "" && nums[0] !== undefined ){
          let a = nums.splice(0,chunkNo) ; 
          newArr.push(a);
        }
      }
       return newArr ;
    }
    console.log(chunkArr(nums, 5));

如果你正在使用下划线JS,只需使用:

var result = _.chunk(arr,elements_per_chunk)

无论如何,大多数项目已经使用下划线作为依赖项。

使用来自lodash的chunk

lodash.chunk(arr,<size>).forEach(chunk=>{
  console.log(chunk);
})