让我们说我有一个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个元素?
当前回答
你可以使用Array.prototype.reduce函数在一行中完成这项工作。
让arr = [1,2,3,4]; 函数块(arr, size) { 令result = arr。减少((行,键,索引)=>(索引%大小== 0 ?rows.push([主要]):行[rows.length-1] .push(关键))& &行,[]); 返回结果; } console.log(块(arr), 2));
其他回答
我稍微改变了BlazeMonger的使用jQuery对象..
var $list = $('li'),
$listRows = [];
for (var i = 0, len = $list.length, chunk = 4, n = 0; i < len; i += chunk, n++) {
$listRows[n] = $list.slice(i, i + chunk);
}
in coffeescript:
b = (a.splice(0, len) while a.length)
demo
a = [1, 2, 3, 4, 5, 6, 7]
b = (a.splice(0, 2) while a.length)
[ [ 1, 2 ],
[ 3, 4 ],
[ 5, 6 ],
[ 7 ] ]
你可以使用Array.prototype.reduce函数在一行中完成这项工作。
让arr = [1,2,3,4]; 函数块(arr, size) { 令result = arr。减少((行,键,索引)=>(索引%大小== 0 ?rows.push([主要]):行[rows.length-1] .push(关键))& &行,[]); 返回结果; } console.log(块(arr), 2));
这是我能想到的最有效、最直接的解决方案:
function chunk(array, chunkSize) {
let chunkCount = Math.ceil(array.length / chunkSize);
let chunks = new Array(chunkCount);
for(let i = 0, j = 0, k = chunkSize; i < chunkCount; ++i) {
chunks[i] = array.slice(j, k);
j = k;
k += chunkSize;
}
return chunks;
}
整洁干净,易于理解
let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let len = nums.length ;
const chunkArr = (arr, chunkNo) => {
let newArr = [];
for(let i = 0; i < len; i++){
if(nums[0] !== "" && nums[0] !== undefined ){
let a = nums.splice(0,chunkNo) ;
newArr.push(a);
}
}
return newArr ;
}
console.log(chunkArr(nums, 5));