举个例子:对以下数组按 lastName 的值进行分组分类
const listData = [
{ firstName: "Rick", lastName: "Sanchez", size: 18 },
{ firstName: "Morty", lastName: "Smith", size: 6 },
{ firstName: "Jerry", lastName: "Smith", size: 3 },
{ firstName: "Beth", lastName: "Smith", size: 0 },
{ firstName: "Summer", lastName: "Smith", size: 0 },
{ firstName: "Rick", lastName: "Sanchez", size: 18 },
{ firstName: "Morty", lastName: "Smith", size: 6 },
];
分组前:
分组后:
一、普通写法
const sortClass = (sortData) => {
const groupBy = (array, f) => {
let groups = {};
array.forEach((o) => {
let group = JSON.stringify(f(o));
groups[group] = groups[group] || [];
groups[group].push(o);
});
return Object.keys(groups).map((group) => {
return groups[group];
});
};
const sorted = groupBy(sortData, (item) => {
return item.lastName; // 返回需要分组的对象
});
return sorted;
};
// 分组前
console.log(listData);
// 分组后
console.log(sortClass(listData));
二、TS 写法
const sortClass = (sortData: ListDataItem[]) => {
const groupBy = (array: ListDataItem[], f: Function) => {
const groups: {
[key: string]: ListDataItem[],
} = {};
array.forEach((item) => {
const group = JSON.stringify(f(item));
groups[group] = groups[group] || [];
groups[group].push(item);
});
return Object.keys(groups).map((group) => {
return groups[group];
});
};
const sorted = groupBy(sortData, (item: ListDataItem) => {
return item.lastName;
});
return sorted;
};
// 分组前
console.log(listData);
// 分组后
console.log(sortClass(listData));