JS 数组 group by 分组

发布时间 2023-04-27 17:56:12作者: NavyW

扩展数组方法

Array.prototype.groupBy = function groupBy(key) {
    const hash = {},
        result = [];
    for (const el of this) {
        if (hash[el[key]]) {
            hash[el[key]].push(el);
        } else {
            result.push({
                key: el[key],
                values: (hash[el[key]] = [el]),
            });
        }
    }
    return result;
};

Array.prototype.key = function (key) {
    return this.map(el => el[key]);
};

Array.prototype.sum = function (key) {
    return this.reduce((total, el) => total + (key ? el[key] : el), 0);
};

Array.prototype.distinct = function () {
    return [...new Set(this)];
};

示例

let arr = [
    { name: 'Tom', sex: 'male', score: 95 },
    { name: 'Alice', sex: 'female', score: 85 },
    { name: 'Bill', sex: 'male', score: 58 },
    { name: 'Jack', sex: 'male', score: 63 },
    { name: 'Mary', sex: 'female', score: 77 },
];

# 按性别分组计算总分
arr.groupBy('sex').map(({key,values})=>({'sex':key,'sum':values.sum('score')}))

# 按性别分组计算人数
arr.groupBy('sex').map(({key,values})=>({'sex':key,'sum':values.length}))