让我们说我有一个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个元素?
当前回答
这是一个递归的解决方案,尾部调用优化。
const splitEvery = (n, xs, y=[]) => xs。长度= = = 0 ?y: splitEvery(n, xs.slice(n), y.concat([xs. slice(n)])片(0,n)))) console.log(splitEvery(2, [0,1,2,3,4,5,6,7,8,9]))
其他回答
这里有一个更具体的案例,有人可能会觉得有价值。我还没看到这里提到过。
如果你不想要固定/均匀的数据块大小,而是想要指定拆分数组的下标怎么办?在这种情况下,你可以使用这个:
const splitArray = (array = [], splits = []) => {
array = [...array]; // make shallow copy to avoid mutating original
const chunks = []; // collect chunks
for (const split of splits.reverse()) chunks.push(array.splice(split)); // go backwards through split indices and lop off end of array
chunks.push(array); // add last remaining chunk (at beginning of array)
return chunks.reverse(); // restore chunk order
};
然后:
splitArray([1, 2, 3, 4, 5, 6, 7, 8, 9], [4, 6])
// [ [1, 2, 3, 4] , [5, 6] , [7, 8, 9] ]
请注意,如果你给它非升序/重复/负/非整数/等分割索引,这将会发生有趣的事情。您可以为这些边缘情况添加检查(例如array .from(new Set(array))来消除重复。
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;
}
这是一个带有尾递归和数组解构的版本。
远非最快的性能,但我只是觉得好笑,js现在可以做到这一点。即使它没有为此进行优化:(
const getChunks = (arr, chunk_size, acc = []) => {
if (arr.length === 0) { return acc }
const [hd, tl] = [ arr.slice(0, chunk_size), arr.slice(chunk_size) ]
return getChunks(tl, chunk_size, acc.concat([hd]))
}
// USAGE
const my_arr = [1,2,3,4,5,6,7,8,9]
const chunks = getChunks(my_arr, 2)
console.log(chunks) // [[1,2],[3,4], [5,6], [7,8], [9]]
下面的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)
你可以使用Array.prototype.reduce函数在一行中完成这项工作。
让arr = [1,2,3,4]; 函数块(arr, size) { 令result = arr。减少((行,键,索引)=>(索引%大小== 0 ?rows.push([主要]):行[rows.length-1] .push(关键))& &行,[]); 返回结果; } console.log(块(arr), 2));