getGroup(arr: any[], name: string | string[]) {
// 单个字符串
if (typeof name === 'string') {
const a = [];
arr.forEach((item1: any) => {
const flag = a.some((item2: any) => item2[name] === item1[name]);
if (!flag) {
a.push(item1);
}
});
return a.map((item1: any) => {
const groupList = arr.filter((item2: any) => item2[name] === item1[name]);
return {
name: item1[name],
groupList
};
});
}
// 多个字符串
if (typeof name === 'object' && name instanceof Array && name.length > 0) {
const a = [];
let b = [];
arr.forEach((item1: any) => {
const obj = {};
name.forEach((item2: any) => {
obj[item2] = item1[item2];
});
b.push(obj);
});
const o = {};
b.reduce((item, next) => {
o[JSON.stringify(next)] ? '' : o[JSON.stringify(next)] = true && item.push(next);
return item;
}, []).map((item1: any) => {
const groupList = [];
arr.filter((item2: any) => {
const flagList = []; // 每个值对比状态
name.forEach((item3: any) => {
flagList.push(item1[item3] === item2[item3]);
});
if (flagList.every((item4: any) => item4 === true)) {
groupList.push(item2);
}
});
a.push({
...item1,
groupList
});
});
return a;
}
return arr;
}