Skip to content

Instantly share code, notes, and snippets.

@iamkeyur
Last active August 7, 2020 15:37
Show Gist options
  • Save iamkeyur/892c3e907d7715128c5bdc7d9f05a3c2 to your computer and use it in GitHub Desktop.
Save iamkeyur/892c3e907d7715128c5bdc7d9f05a3c2 to your computer and use it in GitHub Desktop.
[Array into chunks] Divide an array in multiple chunks of specified size #array #javascript

The array.slice method can extract a slice from the beginning, middle, or end of an array for whatever purposes you require, without changing the original array.

var i,j,temparray,chunk = 10;
for (i=0,j=array.length; i<j; i+=chunk) {
    temparray = array.slice(i,i+chunk);
    // do whatever
}

Recursive method

function chunk(array, size) {
  if (!array) return [];
  const firstChunk = array.slice(0, size); // create the first chunk of the given array
  if (!firstChunk.length) {
    return array; // this is the base case to terminal the recursive
  }
  return [firstChunk].concat(chunk(array.slice(size, array.length), size)); 
}

/*
Let's take an example to make it more easy to understand
chunk([1, 2, 3, 4], 2);
1st call - chunk([1,2 3,4], 2) = [[1,2]].concat(chunk([3,4], 2));
2nd call - chunk([3, 4], 2) = [[3 ,4]].concat(chunk([], 2));
3rd call - chunk([], 2) = [] //base case
so basically, chunk([1, 2, 3, 4], 2) = [[1,2]].concat([[3 ,4]].concat([])) = [[1,2], [3, 4]]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment