让我们说我有一个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个元素?
当前回答
一个有效的解决方案是通过indexChunk将解决方案与slice和push连接起来,解决方案被分割成块:
function splitChunks(sourceArray, chunkSize) { if(chunkSize <= 0) throw "chunkSize must be greater than 0"; let result = []; for (var i = 0; i < sourceArray.length; i += chunkSize) { result[i / chunkSize] = sourceArray.slice(i, i + chunkSize); } return result; } let ar1 = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]; console.log("Split in chunks with 4 size", splitChunks(ar1, 4)); console.log("Split in chunks with 7 size", splitChunks(ar1, 7));
其他回答
使用发电机
函数*块(arr, n) { 对于(设I = 0;I < arrr .length;I += n) { 加勒比海盗。Slice (i, i + n); } } let someArray = [0,1,2,3,4,5,6,7,8,9] console.log([…块(someArray, 2)]) / /[[0, 1],[2、3],[4,5],[6、7],[8 9]]
可以像这样用Typescript输入:
function* chunks<T>(arr: T[], n: number): Generator<T[], void> {
for (let i = 0; i < arr.length; i += n) {
yield arr.slice(i, i + n);
}
}
这里有一个更具体的案例,有人可能会觉得有价值。我还没看到这里提到过。
如果你不想要固定/均匀的数据块大小,而是想要指定拆分数组的下标怎么办?在这种情况下,你可以使用这个:
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))来消除重复。
我最喜欢的是生成器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 ] ]
与许多其他解决方案相比,生成器的一个优点是不会创建多个不必要的数组。
这是一个递归的解决方案,尾部调用优化。
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]))
这是一个带有尾递归和数组解构的版本。
远非最快的性能,但我只是觉得好笑,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]]