Search code examples
javascriptarrayslodash

Group array data with lodash


I have an array of objects and I want to group them as an array of arrays with 10 objects each.

input: data = [{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},....{100}]

output: groupedData = [ [{1},..{10}], [{11},...{20}], ... [{91}, ..{100}] ]

I have tried with lodash _groupBy like this groupedData = _groupBy(data, 10) but the output is undefined: [{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},....{100}]


Solution

  • To achieve what you want to achieve you should use lodash's chunk function. The chunk function creates a new array with subarrays of the given length. Refering to Lodash Docs for chunk.

    _.chunk([{1}, {2}, ..., {100}], 10)