0

first question on stackoverflow, i'm struggling with this algorithm. This is supposed to slice my array in 5 like "[[0, 1], [2, 3], [4, 5], [6, 7], [8]]" but all i got is "[ [ 0, 1 ], [ 2, 3 ], [ 4, 5 ], [ 6, 7, 8 ] ]"

function chunkArrayInGroups(arr, size) {
  var newArr = [];
  console.log(Math.floor(arr.length / size));
  for (i = 0; i <= (Math.floor(arr.length / size)) + 1; ++i) {
    var cut = size;
    newArr.push(arr.splice(0, cut));
  }
  if (arr.length > 0) {
    newArr.push(arr.splice(0, size + (arr.length - size)));
  }
  return newArr;
}
chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2);
// expected - [[0, 1], [2, 3], [4, 5], [6, 7], [8]]

If you have any tips about the way of asking questions, i'd be happy to receive any advice !

3
  • 1
    Welcome to stackoverflow !. This might help you stackoverflow.com/help/how-to-ask get started on how to as a question here on stackoverflow. Commented Dec 1, 2016 at 19:52
  • your algorithm is not working because of this line: for (i = 0; i <= (Math.floor(arr.length / size)) + 1; ++i) {...} witch is for (i = 0; i <= (Math.floor(9 / 2)) + 1; ++i) {...}, initially Math.floor(arr.length / size) is equal 5 but after each execution you shrink your arr.length by size so now you have for (i = 1; i <= (Math.floor(7 / 2)) + 1; ++i) {...} then for (i = 2; i <= (Math.floor(5 / 2)) + 1; ++i) {...} and for (i = 3; i <= (Math.floor(3 / 2)) + 1; ++i) {...} is not going to execute. So you do only 3 executions instead of 5. Hope that makes sense. Commented Dec 1, 2016 at 22:37
  • @brigysl Yes thank you ! I forgot this one.. splice is dangerous ! Commented Dec 1, 2016 at 22:40

7 Answers 7

2

Use a simple for loop with Array#slice, because slice doesn't change the length of the original array:

function chunkArrayInGroups(arr, size) {
  var chunked = [];
  
  for(var i = 0; i < arr.length; i += size) { // increment i by the size
    chunked.push(arr.slice(i, i + size));
  }
  
  return chunked;
}

var result = chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2);

console.log(result);

Sign up to request clarification or add additional context in comments.

1 Comment

I thought the last .slice() must perfectly fit the array index, in this case (0, 1) :o It worked perfectly, thank you !
1

Since you are removing element using Array#splice the array length get decreased so instead of calculating the range cache the range for the for loop condition. Although use Math.ceil and avoid the unnecessary if statement.

function chunkArrayInGroups(arr, size) {
  var newArr = [],
    range = Math.ceil(arr.length / size);

  for (i = 0; i < range; i++) {
    newArr.push(arr.splice(0, size));
  }

  return newArr;
}
console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2));

1 Comment

Care to explain to OP why?
0

Check this out.

function chunkArrayInGroups(arr, size) {
     newArr = [];
     for (i=0,j=arr.length; i<j; i+=size) {
        newArr.push(arr.slice(i,i+size));
     }
    return newArr;
}
console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2));
// expected - [[0, 1], [2, 3], [4, 5], [6, 7], [8]]

Comments

0

Another way to do it is Array#reduce:

function chunkArrayInGroups(arr, size) {
    return arr.reduce(function (accum, elem) {
        var curr = accum[accum.length - 1];
        if (curr.length < size) curr.push(elem); else accum.push([elem]);
        return accum;
    }, [[]]);
}

var result = chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2);
console.log( JSON.stringify(result) );

Comments

0

Welcome to SO. Here is how I would do that. Let me know if you have any questions about this approach.

function chunkArrayInGroups(arr, size) {
  var newArr = [];
  while(arr.length > 0){
    newArr.push(arr.splice(0, size)); 
  }
  return newArr;
}

Comments

0

Functionally you can do as follows;

function chunkArrayInGroups(a,g){
  return Array(Math.ceil(a.length/g)).fill()
                                     .map((_,i) => [a[g*i]].concat(a.slice(g*i+1, g*i+g)));
}

var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8];
 result = [];

result = chunkArrayInGroups(arr,2);
console.log(JSON.stringify(result));

result = chunkArrayInGroups(arr,3);
console.log(JSON.stringify(result));

result = chunkArrayInGroups(arr,4);
console.log(JSON.stringify(result));

Comments

0

You could use a while loop and splice the length of the wanted size for a grouped array.

function chunkArrayInGroups(array, size) {
    var result = [];
    while (array.length) {
        result.push(array.splice(0, size));
    }
    return result;
}

console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.