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 1586
遇见更好的自我
遇见更好的自我 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:40

        function chunkArrayInGroups(arr, size) {
    
      var temp = [];
      var result = [];
    
      for (var a = 0; a < arr.length; a++) {
        if (a % size !== size - 1)
          temp.push(arr[a]);
        else {
          temp.push(arr[a]);
          result.push(temp);
          temp = [];
        }
      }
    
      if (temp.length !== 0)
        result.push(temp);
      return result;
    }
    

提交回复
热议问题