How to split an array into groups

I am writing a function that splits an array (first argument) into groups by 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 or help are 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 or help are appreciated.

+5
source share

Source: https://habr.com/ru/post/1238083/


All Articles