Writing Lodash's Chunk method from scratch

Nritam KumarNritam Kumar
1 min read

The _.chunk method in Lodash is a utility function that splits an array into groups of a specified size. Each group is returned as a sub-array, and the final group may contain fewer elements if there are not enough elements to fill it completely. This method is particularly useful for breaking down large arrays into smaller, more manageable chunks

Example
_.chunk(['a', 'b', 'c', 'd'], 2); // => [['a', 'b'], ['c', 'd']]

export default function chunk<T>(array: Array<T>, size = 1): Array<Array<T>> {
  if(!array.length) return [];
    const returnArr = [];
    let sliceEndCounter = size;
    let sliceStartCounter = 0;
    while (sliceEndCounter < array.length) {
      returnArr.push(array.slice(sliceStartCounter, sliceEndCounter));
      sliceStartCounter = sliceEndCounter;
      sliceEndCounter = sliceEndCounter + size;
    }
    returnArr.push(array.slice(sliceStartCounter));

    return returnArr;
}
0
Subscribe to my newsletter

Read articles from Nritam Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Nritam Kumar
Nritam Kumar