DEV Community

Melvinvmegen
Melvinvmegen

Posted on • Originally published at blog.melvinvmegen.com

Split an array into smaller arrays of a specific size

Image description

Context

As a JavaScript developer, you may need to split an array into smaller arrays of a specific size and while you may be used to the _.chunk(data, size) function from Lodash you can also do it rather easily using only native Javascript. The toChunks function here is the perfect snippet for this task. Let's first find out how it to use it :

Usage

toChunks([1, 2, 3, 4], 1) // [[1], [2], [3], [4]]
toChunks([1, 2, 3, 4], 2) // [[1, 2], [3, 4]]
toChunks([1, 2, 3, 4], 3) // [[1, 2, 3], [4]]
toChunks([1, 2, 3, 4], 4) // [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

Demystify the "toChunks" Function

We can divide the toChunks function into three main parts:

  1. The toChunks function: that takes two arguments array and size, as the size of each desired chunk.
  2. Reduce: The provided array is iterated over by the reduce method which takes two arguments: a callback function and an initial value for the accumulator, here an empty array [].
  3. The callback function: which is executed for every item taking three arguments: the accumulator (arr), the current item in the array, and his index (idx).

How it works

To provide a more concrete example i will base the explanation on this example :

toChunks([1, 2, 3, 4], 2) // [[1, 2], [3, 4]]
Enter fullscreen mode Exit fullscreen mode
  1. First, the callback function running on each item will check if the current index is divisible by the size argument (2) using the remainder operator %.
  2. If it does, then we will create a new chunk with the current item before adding it to the accumulator using the spread operator ..., in case of our example, after one iteration the accumulator would look like that [[1]].
  3. Otherwise, it means that we need to add the current item to the last chunk in the accumulator. To do so, the slice method is used to extract the last element of the accumulator (which after the first iteration is still [1]) before adding the current item with the mighty spread operator "..." so that after the second iteration we have [1, 2]. Then, we replace the last element of the accumulator with the updated chunk again using the slice method so that we end up with this value [[1, 2]].
  4. After every iteration placing each item inside the right chunk, the reduce method returns the accumulator, so that we end up with an array of smaller arrays with the values of the original array.

And tada 🎉

toChunks([1, 2, 3, 4], 2) // [[1, 2], [3, 4]]
Enter fullscreen mode Exit fullscreen mode

Conclusion

The toChunks function is the perfect snippet for splitting an array into smaller arrays of a specific size. By properly using the powers of reduce, slice and the spread operator, we can easily create such a function only using native JavaScript instead of Lodash.

Top comments (0)