-3

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}]

user2004
  • 1,783
  • 4
  • 15
  • 42
  • What makes you think that `_groupBy(data, 10)` (is this missing a `.`/is this actually lodash?) would cut the array in chunks of size `10`? – Andreas Mar 03 '22 at 09:03
  • 1
    Does this answer your question? [Convert a 1D array to 2D array](https://stackoverflow.com/questions/22464605/convert-a-1d-array-to-2d-array) – Kordrad Mar 03 '22 at 09:05

2 Answers2

1

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)
Palladium02
  • 1,134
  • 1
  • 4
  • 13
1

If you want Vanilla JS then you can try this

const data = [{1:1},{2:2},{3:3},{4:4},{5:5},{6:6},{7:7},{8:8},{9:9},{10:10},{1:1},{2:2},{3:3},{4:4},{5:5},{6:6},{7:7},{8:8},{9:9},{10:10},{1:1},{2:2},{3:3},{4:4},{5:5},{6:6},{7:7}];

const groupeData = (arr, groupCount) => {
    const result = [];
    let tempArr = [];

    for (const obj of data) {
        tempArr.push(obj);

        if (tempArr.length === groupCount) {
            result.push(tempArr);
            tempArr = [];
        }
    }

    if (tempArr.length !== 0) result.push(tempArr);
    
    return result;
}

const groupedData = groupeData(data, 10);


console.log(groupedData); // Array(3) [ (10) […], (10) […], (7) […] ]
EzioMercer
  • 1,502
  • 2
  • 7
  • 23