javascript的groupby操作用法

bigdata.ministep.cn / 2023-09-07 / 原文

示例:


const pets = [
    {type:"Dog", name:"Spot"},
    {type:"Cat", name:"Tiger"},
    {type:"Dog", name:"Rover"}, 
    {type:"Cat", name:"Leo"}
];
const groupByCombine = (items, key) => items.reduce(
  (result, item) => ({
    ...result,
    [item[key]]: [
      ...(result[item[key]] || []),
      item,
    ],
  }), 
  {},
);  
groupByCombine(pets,'type')

参考:

javascript - Most efficient method to groupby on an array of objects - Stack Overflow