Home > Back-end >  Group array data with lodash
Group array data with lodash

Time:03-03

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

CodePudding user response:

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)

CodePudding user response:

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) […] ]
  • Related