让我们说我有一个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个元素?
当前回答
Const array = ['a', 'b', 'c', 'd', 'e']; Const size = 2; Const chunks = []; While (array.length) { chunks.push(数组。拼接(0,大小)); } console.log(块);
其他回答
最有效的方法是将数组视为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相同。
附:我是图书馆的作者。
老问题:新答案!事实上,我一直在想这个问题的答案,并让一个朋友改进了它!就是这样:
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]]
你可以使用这个ES6块函数,它很容易使用:
Const chunk = (array, size) => Array.from({长度:Math.ceil(数组。Length / size)}, (value, index) =>数组。切片(索引*大小,索引*大小+大小)); const itemsPerChunk = 3; const inputArray = [a, b, c, d, e, f, g的); const newArray = chunk(inputArray, itemsPerChunk); console.log (newArray.length);/ / 3, document . write (JSON.stringify (newArray));/ / [[' a ', ' b ', ' c '], [' d ', ' e ', ' f '], [g]]
我的技巧是使用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; }
这应该是一个简单的答案,没有太多的数学复杂性。
function chunkArray(array, sizeOfTheChunkedArray) {
const chunked = [];
for (let element of array) {
const last = chunked[chunked.length - 1];
if(!last || last.length === sizeOfTheChunkedArray) {
chunked.push([element])
} else {
last.push(element);
}
}
return chunked;
}