Hi,
I just seem to get arrays split up given back to me, can anybody help me see where I’m going wrong? Probably in lots of places. Thanks!
function chunkArrayInGroups(arr, size) {
// Break it up.
var newArr = [];
for (let i = 0; i < arr.length; i++) {
newArr.push(arr.splice(0, size));
}
return newArr;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);
You shouldn’t use splice
here as doing so mutates arr
, which you are also using to loop over. Instead use slice
(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice). You can use it to copy the parts of arr
that you need. Also, you shouldn’t increment i
by 1 on each loop iteration. Instead, increase it by size
.
wawraf
3
Method splice changes the original array, hence every iteration arr.length value is changing.
Try to change your function a little that it iterates number of times depending on two provided arguments.
EDIT:
As joops75 said you can use slice method which has better performance however you can achieve correct result easily using both methods.