Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Let's Chunk

DZone's Guide to

Let's Chunk

We review how to use the chunk function in JavaScript, which allows use to more easily work with and generate array.

· Web Dev Zone ·
Free Resource

Jumpstart your Angular applications with Indigo.Design, a unified platform for visual design, UX prototyping, code generation, and app development.

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 those libraries here, but, instead, for the practice, let’s write in pure JavaScript one of Lodash’s neat functions, called chunk.

The chunk function takes an array and a number (let’s call it num) as parameters. The function returns a new array containing all the original array’s elements organized into 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 are 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-element 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:

Cool, ah?

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;
}

So this is how we implement 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?

Take a look at an Indigo.Design sample application to learn more about how apps are created with design to code software.

Topics:
lodash ,web dev ,javascript libraries ,javascript tutorials ,chunk function

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}