# Let’s Chunk

3 min readDec 15, 2018

--

There is huge amount of Javascript libraries that give us all kinds of functionality — DOM manipulations, AJAX calls, animations, DB querying, you name it. There is a library (and usually more than one) for everything. All those functions provided by the libraries can be done, of course, in pure Javascript.

Lodash and Underscore are two such libraries. They are very useful and contain a lot of utility functions that can make our life as Javascript programmers easier. I won’t describe here those libraries, but instead, for the practice, let’s write in pure Javascript one of Lodash’s neat function, called chunk.

The chunk function takes as parameters an array and a number (let’s call it num). The function returns a new array containing all the original array’s elements organized in chunks with the size of num. What it means is that we pass an array and get back an array of arrays, each of them (besides, maybe, the last) is in the length of num.

For example, if we had this array –

`var a = [1, 2, 3, 4, 5, 6, 7, 8];`

We could call the chunk function as follows (the results in the comments):

`var b = chunk(a, 2); // b = [[1, 2], [3, 4], [5, 6], [7, 8]]b = chunk(a, 3);     // b = [[1, 2, 3], [4, 5, 6], [7, 8]]b = chunk(a, 5)      // b = [[1, 2, 3, 4, 5], [6, 7, 8]]`

So how are we going to write that?

Most of the work is pretty simple — we take the next num elements from the array, push them to a new array and push this array to the result array. For example, given the array a from above, if we want to create 3-elements chunks, we would take the first three elements of the array — 1, 2, 3 — and put them in a new array, and then put this new array into the result — [[1, 2, 3]]. Then we’ll take the next three elements — 4, 5, 6 — and again put them into a new array and push it to the result — [[1, 2, 3], [4, 5, 6]].

This process would continue until we don’t have enough elements to fill a chunk. In this case, all the elements that are left just put into a new array. In this example the numbers 7 and 8 would be alone in the last chunk. How do we know that we don’t have enough elements to fill a chunk? If the index we’re in is bigger than the array length minus num. Try it with examples and see it’s correct. So here is the code:

`function chunk(a, num) {   var res = [];   var i = 0;   while(i <= a.length — num) {      var chunk = Array(num);      for(var j = 0; j < num; j++)         chunk[j] = a[i + j];      res.push(chunk);      i += num;   }   if(i < a.length)      res.push(a.slice(i));   return res;}`

Cool, ah?

So this is how we implemented the chunk function, and again, using lodash.js we would get this function for free but hey, it was fun doing it by ourselves, wasn’t it?

In the next article I’ll try to show an example for using this function, until then, try to think what would the function return if num was bigger than the array’s length? Or if it was negative? Or if the array was empty?