5

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

so that

 1. chunk(["a", "b", "c", "d"], 2) should return [["a", "b"], ["c", "d"]].
 2. chunk([0, 1, 2, 3, 4, 5], 3) should return [[0, 1, 2], [3, 4, 5]].
 3. chunk([0, 1, 2, 3, 4, 5], 2) should return [[0, 1], [2, 3], [4, 5]].
 4. chunk([0, 1, 2, 3, 4, 5], 4) should return [[0, 1, 2, 3], [4, 5]].

What is wrong with my function?
Any suggestions and help is appreciated.

  function chunk(arr, size) {
      var newArray2 = [];
      var len = 0;
      for(i=0; i < Math.ceil(arr.length/size); i++)
          { var newArray1 = [];
             for(var j=0; j < Math.ceil(arr.length/size); j++)
               {
                 if (len < arr.length)
                   {
                     newArray1[j] = arr[len];
                   }
                 len = len + 1;
                }
            newArray2[i] = newArray1;
          }
     
      return newArray2;
      //return Math.ceil(arr.length/size);
      //return arr.length/(arr.length/size);
    }
chunk([0, 1, 2, 3, 4, 5], 4);

What is wrong with my function.? Any suggestions and help is appreciated.

Abhash Upadhyaya
  • 717
  • 14
  • 34
user2816085
  • 655
  • 4
  • 19
  • Did you get an error? – Clay Dec 14 '15 at 09:23
  • 1
    Your function could be much simpler. Have you heard about Array's [`slice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice)? – hindmost Dec 14 '15 at 09:27
  • Can you elaborate on how your code doesn't work? What were you expecting, and what actually happened? If you got an exception, post the line it occurred on and the exception details. – Kyll Dec 14 '15 at 09:39
  • I was taking as **arr.length/(arr.length/size)** == **Math.ceil(arr.length/size)** == **arr.length/size** but now i got it. thanks. – user2816085 Dec 14 '15 at 12:56
  • This is called "partitioning". *What is wrong with my function?* I don't know--does it work? –  Dec 14 '15 at 12:58

0 Answers0