javascript的groupby操作用法
示例:
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
高级用法
lodash - group and populate arrays - Stack Overflow
参考:
https://stackoverflow.com/questions/57234403/use-lodash-groupby-function-to-categorize-objects-in-an-array