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

    function chunk(arr, size) {
      var newArr = [];
      // x is less than or equals arr.length.
      for(var x = 0; x <= arr.length; x++){
         newArr.push(arr.splice(0, size));
      }
    
      if (arr.length){
         newArr.push(arr);
      }
      return newArr;
    }
    
    chunk(['a', 'b', 'c', 'd'], 2);
    

提交回复
热议问题