js array groupby 数组分组

发布时间 2023-06-09 10:02:27作者: 87的海雷
/**
 * 组件名称
 * @module tool.js
 * @desc 数据分组
 * @author DHL
 * @date 2017年12月05日17:22:43
 * @param { Function } func - 方法
 * @example 调用示例
 *  [].groupBy(x=>({a:x.a,b:x.b})
 *  [].groupBy(x=>x.a)
 **/
Array.prototype.groupBy = function(fn) {
    return Array.from(new Set(this.map(x => JSON.stringify(fn(x))))).map(x => ({
        key: JSON.parse(x),
        items: this.filter(p => JSON.stringify(fn(p)) === x)
    }))
}