in Work

JS : Splitting an array into batches

In order to meet the limits on a REST API call, I needed to split a batch of record IDs into batches the size of the call’s limit.  Since I was doing this in NodeJS, I worked it out functionally with the .reduce() method.  [The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.]  In this case, my single value target was an array of arrays.

There trick here was use a little index magic and pass in an array of empty arrays as the initial value parameter where the number of empty arrays equaled the desired number of batches.

The effect is that 1, 3, 5, and 7 go into the first batch and 2, 4, 6, and 8 go into the second.  This is acceptable for my purposes, but you might want to use a little different index magic to get the batches in order.

You can run it online with this jsFiddle.


Write a Comment