让我们说我有一个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个元素?
当前回答
这是我使用的,它可能不是超级快,但它是紧凑和简单:
让chunksplit = (stream, size) => stream。Reduce ((chunk, item, idx, arr) => (idx % size == 0) ?[…块,加勒比海盗。Slice (idx, idx + size)]: chunk, []); //如果索引是chunksize的倍数,则添加新数组 让testArray =[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12日,13日,14日,15日,16日,17日,18日,19日,20日,21日,22日); document . write (JSON。stringify(chunksplit(testArray, 5)); / /使用JSON。要显示的嵌套数组的Stringify
其他回答
下面的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)
这里是一个仅使用递归和slice()的非突变解决方案。
const splitToChunks = (arr, chunkSize, acc = []) => (
arr.length > chunkSize ?
splitToChunks(
arr.slice(chunkSize),
chunkSize,
[...acc, arr.slice(0, chunkSize)]
) :
[...acc, arr]
);
然后简单地像splitToChunks([1,2,3,4,5], 3)一样使用它来获得[[1,2,3],[4,5]]。
这里有一个小提琴供你尝试:https://jsfiddle.net/6wtrbx6k/2/
下面是一个使用ImmutableJS的解决方案,其中items是一个不可变列表,size是所需的分组大小。
const partition = ((items, size) => {
return items.groupBy((items, i) => Math.floor(i/size))
})
她是一个简单的解决方案使用@Blazemonger解决方案
function array_chunk(arr, size){
// initialize vars
var i,
j = arr.length,
tempArray = [];
// loop through and jump based on size
for (i=0; i<j; i+=size) {
// slice chunk of arr and push to tempArray
tempArray.push(arr.slice(i,i+size));
}
// return temp array (chunck)
return tempArray
}
这让我的管道流动起来,希望这能帮助到其他人。:)
一个很好的函数是:
function chunk(arr,times){
if(times===null){var times = 10} //Fallback for users wanting to use the default of ten
var tempArray = Array() //Array to be populated with chunks
for(i=0;i<arr.length/times;i++){
tempArray[i] = Array() //Sub-Arrays //Repeats for each chunk
for(j=0;j<times;j++){
if(!(arr[i*times+j]===undefined)){tempArray[i][j] = arr[i*times+j]//Populate Sub- Arrays with chunks
}
else{
j = times //Stop loop
i = arr.length/times //Stop loop
}
}
}
return tempArray //Return the populated and chunked array
}
用法如下:
chunk(array,sizeOfChunks)
我对它做了注释,这样你就能理解发生了什么。
(格式有点不对,我在移动设备上编程)