Rashid Rashid - 2 years ago 104
Javascript Question

Splitting an array into groups

I am expected to write a function that splits an array (first argument) into groups the length of size (second argument) and returns them as a two-dimensional array.
Therefore, chunkArrayInGroups(["a", "b", "c", "d"], 2) should return [["a", "b"], ["c", "d"]]

function chunkArrayInGroups(arr, size) {
// Break it up.
var result=[];
for (var i=0;i<=Math.ceil(arr.length/size);i++){

var j=0;
if(i!== 0){

result[i] = arr.slice(j , size);

//return arr.length/size
//results in 1.5

return result;
// results [["a", "b"], ["c", "d"]]


chunkArrayInGroups(["a", "b", "c", "d"], 2);

I am getting the desired result but I'm not very satisfied with my solution,
also, more importantly
"if" arr.length = 4; and, size =2; then why is arr.length/size = 1 ?
shouldn't it be 4/2=2?

Answer Source

You modify size inside the loop. This basically doubles the size at every step. The fact that your example only has two sub-arrays hides this problem. Try larger arrays to see the problem in the result.

To fix this, declare j outside of the loop. Add the size to j after slicing.

Edit: Code, as requested

function chunkArrayInGroups(arr, size) {
  var result = [];
  var j = 0;
  for (var i = 0; i <= Math.ceil(arr.length / size); i++) {
    result[i] = arr.slice(j, j + size);
    j = j + size;
  return result;

Or, slightly simplified:

function chunkArrayInGroups(arr, size) {
  var result = [];
  var pos = 0;
  while (pos < size) {
    result.push(arr.slice(pos, pos + size);
    pos += size;
  return result;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download