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

    So many Ways...

    function chunkArrayInGroups(arr, size) {
     var value = [];
    
    for(var i =0; i<arr.length; i += size){
     value.push(arr.slice(i, size+i));
    }
    
    return value;
    }
    
    chunkArrayInGroups(["a", "b", "c", "d"], 2);
    
    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
  • 2020-12-30 18:39
    function chunk(arr, size) {
      var newArr = []; // New empty array
      while (arr.length > 0) { // Loop thru the array items
        newArr.push(arr.splice(0, size)); // Removes first 2 items then add it to new array
      }
      return newArr; // New 2D array
    }
    

    I tried using these lines of codes in console and it worked perfectly fine.

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2020-12-30 18:46
    function chunkArrayInGroups(arr, size) {
      var result = [],
          iterations = Math.ceil(arr.length/size);
      for (var i =0; i<iterations;i++){
          var sub = arr.splice(0, size);
          result.push(sub);
      }
      return result;       
    }
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
提交回复
热议问题