Verwendung von Array.prototype.splice()
und spleißt es, bis das Array ein Element hat.
Array.prototype.chunk = function(size) {
let result = [];
while(this.length) {
result.push(this.splice(0, size));
}
return result;
}
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(arr.chunk(2));
Update
Array.prototype.splice()
das ursprüngliche Array auffüllt und nach der Durchführung der chunk()
das ursprüngliche Array ( arr
) wird []
.
Wenn Sie also das ursprüngliche Array unangetastet lassen wollen, kopieren Sie und behalten Sie die arr
Daten in ein anderes Array zu übertragen und das Gleiche zu tun.
Array.prototype.chunk = function(size) {
let data = [...this];
let result = [];
while(data.length) {
result.push(data.splice(0, size));
}
return result;
}
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log('chunked:', arr.chunk(2));
console.log('original', arr);
P.S.: Dank an @mts-knn für den Hinweis auf die Angelegenheit.