让我们说我有一个Javascript数组看起来如下:
["Element 1","Element 2","Element 3",...]; // with close to a hundred elements.
什么样的方法适合将数组分成许多更小的数组,假设最多有10个元素?
让我们说我有一个Javascript数组看起来如下:
["Element 1","Element 2","Element 3",...]; // with close to a hundred elements.
什么样的方法适合将数组分成许多更小的数组,假设最多有10个元素?
当前回答
我最喜欢的是生成器generateChunks和附加函数getChunks来执行生成器。
function* generateChunks(array, size) {
let start = 0;
while (start < array.length) {
yield array.slice(start, start + size);
start += size;
}
}
function getChunks(array, size) {
return [...generateChunks(array, size)];
}
console.log(getChunks([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 3)) // [ [ 0, 1, 2 ], [ 3, 4, 5 ], [ 6, 7, 8 ], [ 9 ] ]
作为这里的补充,生成器使用进一步的getPartitions函数生成分区,以获得n个相同大小的数组。
function generatePartitions(array, count) {
return generateChunks(array, Math.ceil(array.length / count));
}
function getPartitions(array, count) {
return [...generatePartitions(array, count)];
}
console.log(getPartitions([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 3)) // [ [ 0, 1, 2, 3 ], [ 4, 5, 6, 7 ], [ 8, 9 ] ]
与许多其他解决方案相比,生成器的一个优点是不会创建多个不必要的数组。
其他回答
基于数组的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]]
使用来自lodash的chunk
lodash.chunk(arr,<size>).forEach(chunk=>{
console.log(chunk);
})
使用array .prototype.splice()并拼接它,直到数组有元素。
Array.prototype.chunk = function(size) { Let result = []; 而(this.length) { result.push(这一点。拼接(0,大小)); } 返回结果; } Const arr = [1,2,3,4,5,6,7,8,9]; console.log (arr.chunk (2));
更新
array .prototype.splice()填充原始数组,在执行chunk()之后,原始数组(arr)变成[]。
如果你想保持原始数组不变,那就复制arr数据到另一个数组,然后做同样的事情。
Array.prototype.chunk = function(size) { Let data =[…this]; Let result = []; 而(data.length) { result.push(数据。拼接(0,大小)); } 返回结果; } Const arr = [1,2,3,4,5,6,7,8,9]; console.log(分块:,arr.chunk (2)); console.log(“原始”,arr);
附注:感谢@mts-knn提到这件事。
现在你可以使用lodash的chunk函数将数组分割成更小的数组https://lodash.com/docs#chunk不再需要摆弄循环了!
你可以使用这个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]]