I'm trying to divide an array into subarrays base on the length of the given size, I almost got it but the result has some issue.
[Array(2), empty, Array(2)] // I don't know why there's an empty field in array?
0: (2) [1, 2]
2: (2) [3, 4]
function chunks(array, size) {
var chunk = new Array(size);
for (let i = 0; i < array.length; i += size) {
chunk[i] = array.slice(i, i + size);
}
return chunk;
}
console.log(chunks([1, 2, 3, 4], 2))
The output should be:
[[ 1, 2], [3, 4]]