My example:
let arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18];
let slice = (source, index) => source.slice(index, index + 4);
let length = arr.length;
let index = 0;
let result = [];
while (index < length) {
let temp = slice(arr, index);
result.push(temp);
index += 4;
}
console.log(result);
Logging:
[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16],[17,18]]
I want to slice the array to multiple parts for per 4 items [1,2,3,4] [5,6,7,8]...
The code is working fine.
I have 2 questions:
1/. Is there another way to do that via using inline code? Ex: result = arr.slice(...)
2/. After I define:
let push = result.push;
why cannot I still use:
push(temp)
Error message:
Uncaught TypeError: Array.prototype.push called on null or undefined
UPDATE: I've updated the solution based on the answers. Hope it's helpful.
let arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18];
let result = [];
arr.forEach((x,y,z) => !(y % 4) ? result.push(z.slice(y, y + 4)) : '');
console.log(result);
Logging:
[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16],[17,18]]