const toChunks = (array, size) => {
return array.reduce((arr, item, idx) => {
return idx % size === 0
? [...arr, [item]]
: [...arr.slice(0, -1), [...arr.slice(-1)[0], item]];
}, []);
};
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 :
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]
We can divide the toChunks function into three main parts:
To provide a more concrete example i will base the explanation on this example :
toChunks([1, 2, 3, 4], 2) // [[1, 2], [3, 4]]
[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]].And tada 🎉
toChunks([1, 2, 3, 4], 2) // [[1, 2], [3, 4]]
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.
Honestly i am no one, i've just been coding for 3 years now and i like to document every solutions to every problem i encounter. Extracting as much code snippets and tutorials i can so that if i ever need it again i just have to pop back here and get a quick refresher.
Feel free to me through this learning journey by providing any feedback and if you wanna support me: