Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting an array up into chunks of a given size [duplicate]

Tags:

javascript

I have written a function which takes two parameters: (1) an Array, (2) size of the chunk.

function chunkArrayInGroups(arr, size) {

  var myArray = [];

  for(var i = 0; i < arr.length; i += size) {
    myArray.push(arr.slice(i,size));
  }

  return myArray;
}

I want to split this array up into chunks of the given size.

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

should return: [["a", "b"], ["c", "d"]].

I get back: [["a", "b"], []]

like image 878
Kōdo no musō-ka Avatar asked Nov 18 '16 16:11

Kōdo no musō-ka


1 Answers

You misunderstood what the slice parameters mean. The second one is the index until which (not included) you want to get the subarray. It's not a length.

array.slice(from, to); // not array.slice(from, length)

function chunkArrayInGroups(arr, size) {
  var myArray = [];
  for(var i = 0; i < arr.length; i += size) {
    myArray.push(arr.slice(i, i+size));
  }
  return myArray;
}
console.log(chunkArrayInGroups(["a", "b", "c", "d"], 2));
like image 119
Oriol Avatar answered Oct 13 '22 19:10

Oriol