让我们说我有一个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 ] ]
与许多其他解决方案相比,生成器的一个优点是不会创建多个不必要的数组。
其他回答
这里有一个更具体的案例,有人可能会觉得有价值。我还没看到这里提到过。
如果你不想要固定/均匀的数据块大小,而是想要指定拆分数组的下标怎么办?在这种情况下,你可以使用这个:
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))来消除重复。
的例子 未更改的源数组 不要一次做所有的块。(内存节省!)
const array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21];
const chunkSize = 4
for (var i = 0; i < array.length; i += chunkSize) {
const chunk = array.slice(i, i + chunkSize);
console.log('chunk=',chunk)
// do whatever
}
console.log('src array didnt changed. array=',array)
最有效的方法是将数组视为Iterable,并进行惰性分页。这样,它将只在请求时生成数据。下面的代码使用了iter-ops库中的操作符页:
import {pipe, page} from 'iter-ops';
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; // some input data
const i = pipe(arr, page(2)); //=> Iterable<number>
console.log(...i); //=> [ 1, 2 ] [ 3, 4 ] [ 5, 6 ] [ 7, 8 ] [ 9 ]
工作方式与任何Iterable或AsyncIterable相同。
附:我是图书馆的作者。
打印稿版本。演示了将101个随机uid分成10个组
const idArrayLengthLimit = 10;
const randomOneHundredOneIdArray = Array
.from(Array(101).keys())
.map(() => generateUid(5));
function generateUid(length: number) {
const uidString: string[] = [];
const uidChars = 'abcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < length; i++) {
uidString
.push(uidChars.charAt(Math.floor(Math.random() * uidChars.length)));
}
return uidString.join('');
}
for (let i = 0; i < randomOneHundredOneIdArray.length; i++) {
if(i % idArrayLengthLimit === 0){
const result = randomOneHundredOneIdArray
.filter((_,id) => id >= i && id < i + idArrayLengthLimit);
// Observe result
console.log(result);
}
}
使用来自lodash的chunk
lodash.chunk(arr,<size>).forEach(chunk=>{
console.log(chunk);
})