Write a function that splits an array (first argument) into groups the length of size (second argument) and returns them as a multidimensional array

后端 未结 9 1562
遇见更好的自我
遇见更好的自我 2020-12-30 18:18

I am working through a javascript problem that asks me to:

Write a function that splits an array (first argument) into groups the length of size (second argument) an

9条回答
  •  北海茫月
    2020-12-30 18:37

    The problem is that you are both advancing i by size at each iteration and removing size elements from position i. This causes you to skip processing every other chunk. Also, your continuation condition should be i < arr.length-size; as it is, you would need to test for an empty temp before pushing it after the loop exits. Try rewriting your loop as:

    for (i = 0; i < arr.length-size;){
        newArray.push(arr.slice(i,i+size));
        temp.splice(i,size);
    }
    

    Since i is always at 0, the loop can be simplified to:

    while (arr.length > size) {
        newArray.push(arr.slice(0,size));
        temp.splice(0,size);
    }
    

提交回复
热议问题