让我们说我有一个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个元素?
当前回答
试试这个:
var oldArray =[“香蕉”、“橙色”,“柠檬”、“苹果”、“芒果”,“香蕉”,“橙色”,“柠檬”、“苹果”、“芒果”,“香蕉”,“橙色”,“柠檬”、“苹果”、“芒果”,“香蕉”,“橙色”,“柠檬”、“苹果”、“芒果”,“香蕉”,“橙色”,“柠檬”、“苹果”、“芒果”); var newArray = []; 而(oldArray.length) { 让start = 0; 让end = 10; newArray.push (oldArray。片(开始、结束)); oldArray。拼接(开始、结束); } console.log (newArray);
其他回答
你可以使用Array.prototype.reduce函数在一行中完成这项工作。
让arr = [1,2,3,4]; 函数块(arr, size) { 令result = arr。减少((行,键,索引)=>(索引%大小== 0 ?rows.push([主要]):行[rows.length-1] .push(关键))& &行,[]); 返回结果; } console.log(块(arr), 2));
为这个https://www.npmjs.com/package/array.chunk创建一个npm包
var result = [];
for (var i = 0; i < arr.length; i += size) {
result.push(arr.slice(i, size + i));
}
return result;
当使用TypedArray时
var result = [];
for (var i = 0; i < arr.length; i += size) {
result.push(arr.subarray(i, size + i));
}
return result;
老问题:新答案!事实上,我一直在想这个问题的答案,并让一个朋友改进了它!就是这样:
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]]
results = []
chunk_size = 10
while(array.length > 0){
results.push(array.splice(0, chunk_size))
}
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 ] ]