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

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

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


当前回答

你可以使用这个ES6块函数,它很容易使用:

Const chunk = (array, size) => Array.from({长度:Math.ceil(数组。Length / size)}, (value, index) =>数组。切片(索引*大小,索引*大小+大小)); const itemsPerChunk = 3; const inputArray = [a, b, c, d, e, f, g的); const newArray = chunk(inputArray, itemsPerChunk); console.log (newArray.length);/ / 3, document . write (JSON.stringify (newArray));/ / [[' a ', ' b ', ' c '], [' d ', ' e ', ' f '], [g]]

其他回答

使用来自lodash的chunk

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

为这个https://www.npmjs.com/package/array.chunk创建一个npm包

var result = [];

for (var i = 0; i < arr.length; i += size) {
  result.push(arr.slice(i, size + i));
}
return result;

当使用TypedArray时

var result = [];

for (var i = 0; i < arr.length; i += size) {
  result.push(arr.subarray(i, size + i));
}
return result;

我更喜欢使用splice方法:

var chunks = function(array, size) {
  var results = [];
  while (array.length) {
    results.push(array.splice(0, size));
  }
  return results;
};

基于数组的ES6一行方法。原型缩减和推送方法:

const doChunk = (list, size) => list.reduce((r, v) =>
  (!r.length || r[r.length - 1].length === size ?
    r.push([v]) : r[r.length - 1].push(v)) && r
, []);

console.log(doChunk([0,1,2,3,4,5,6,7,8,9,10,11,12], 5));
// [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12]]

这是我能想到的最有效、最直接的解决方案:

function chunk(array, chunkSize) {
    let chunkCount = Math.ceil(array.length / chunkSize);
    let chunks = new Array(chunkCount);
    for(let i = 0, j = 0, k = chunkSize; i < chunkCount; ++i) {
        chunks[i] = array.slice(j, k);
        j = k;
        k += chunkSize;
    }
    return chunks;
}