让我们说我有一个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个元素?
当前回答
ES6传播功能#ohmy #ftw
Const chunk = (size, xs) => xs.reduce ( (segments, _, index) => 索引%大小=== 0 ? […段,x。Slice (index, index + size)] 段, [] ); console.log(块(3,(1,2,3,4,5,6,7,8)));
其他回答
一个很好的函数是:
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)
我对它做了注释,这样你就能理解发生了什么。
(格式有点不对,我在移动设备上编程)
我的技巧是使用parseInt(i/chunkSize)和parseInt(i%chunkSize),然后填充数组
// filling items let array = []; for(let i = 0; i< 543; i++) array.push(i); // printing the splitted array console.log(getSplittedArray(array, 50)); // get the splitted array function getSplittedArray(array, chunkSize){ let chunkedArray = []; for(let i = 0; i<array.length; i++){ try{ chunkedArray[parseInt(i/chunkSize)][parseInt(i%chunkSize)] = array[i]; }catch(e){ chunkedArray[parseInt(i/chunkSize)] = []; chunkedArray[parseInt(i/chunkSize)][parseInt(i%chunkSize)] = array[i]; } } return chunkedArray; }
我更喜欢使用splice方法:
var chunks = function(array, size) {
var results = [];
while (array.length) {
results.push(array.splice(0, size));
}
return results;
};
她是一个简单的解决方案使用@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
}
这让我的管道流动起来,希望这能帮助到其他人。:)
老问题:新答案!事实上,我一直在想这个问题的答案,并让一个朋友改进了它!就是这样:
Array.prototype.chunk = function ( n ) {
if ( !this.length ) {
return [];
}
return [ this.slice( 0, n ) ].concat( this.slice(n).chunk(n) );
};
[1,2,3,4,5,6,7,8,9,0].chunk(3);
> [[1,2,3],[4,5,6],[7,8,9],[0]]