使用 lodash 对数组数据进行分组

Group array data with lodash

我有一个对象数组,我想将它们分组为一个数组数组,每个数组包含 10 个对象。

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

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

我试过像这样使用 lodash _groupBy groupedData = _groupBy(data, 10) 但输出是 undefined: [{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},....{100}]

要实现你想要实现的目标,你应该使用 lodash 的块功能。 chunk 函数使用给定长度的子数组创建一个新数组。参考Lodash Docs for chunk.

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

如果你想要 Vanilla JS 那么你可以试试这个

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