Js新标准有groupBy了,但你的环境还没有,你需要这个

174 阅读1分钟

就冲它省的那点代码,groupBy确实是个好东西。

const people = [
  { name: "Alice", age: 28 },
  { name: "Bob", age: 30 },
  { name: "Eve", age: 28 },
];

const peopleByAge = {};

people.forEach((person) => {
  const age = person.age;
  if (!peopleByAge[age]) {
    peopleByAge[age] = [];
  }
  peopleByAge[age].push(person);
});

直接写成

const peopleByAge = Object.groupBy(people, (person) => person.age);

如果你目前无法用,不妨加上这个

/**
 * Group an array of objects by a specified key function.
 * @param {Function} keyFunc The function used to extract the key for grouping.
 * @returns {Object} An object where keys are the grouped keys and values are arrays of matching objects.
 */
Object.prototype.groupBy = Object.prototype.groupBy||function(keyFunc) {
    return this.reduce((acc, item) => {
        const key = keyFunc(item);
        acc[key] = acc[key] || [];
        acc[key].push(item);
        return acc;
    }, {});
};

为ts环境添加groupBy定义

// 在 global.d.ts 或者单独的声明文件中添加以下内容 
declare global { 
    interface Object { 
        groupBy(keyFunc: (item: any) => any): { [key: string]: any[] }; 
    }
}