first question on stackoverflow, i'm struggling with this algorithm. This is supposed to slice my array in 5 like "[[0, 1], [2, 3], [4, 5], [6, 7], [8]]" but all i got is "[ [ 0, 1 ], [ 2, 3 ], [ 4, 5 ], [ 6, 7, 8 ] ]"
function chunkArrayInGroups(arr, size) {
var newArr = [];
console.log(Math.floor(arr.length / size));
for (i = 0; i <= (Math.floor(arr.length / size)) + 1; ++i) {
var cut = size;
newArr.push(arr.splice(0, cut));
}
if (arr.length > 0) {
newArr.push(arr.splice(0, size + (arr.length - size)));
}
return newArr;
}
chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2);
// expected - [[0, 1], [2, 3], [4, 5], [6, 7], [8]]
If you have any tips about the way of asking questions, i'd be happy to receive any advice !
for (i = 0; i <= (Math.floor(arr.length / size)) + 1; ++i) {...}witch isfor (i = 0; i <= (Math.floor(9 / 2)) + 1; ++i) {...}, initiallyMath.floor(arr.length / size)is equal 5 but after each execution you shrink yourarr.lengthbysizeso now you havefor (i = 1; i <= (Math.floor(7 / 2)) + 1; ++i) {...}thenfor (i = 2; i <= (Math.floor(5 / 2)) + 1; ++i) {...}andfor (i = 3; i <= (Math.floor(3 / 2)) + 1; ++i) {...}is not going to execute. So you do only 3 executions instead of 5. Hope that makes sense.