js将数组中相同的元素进行分组必看

it2022-12-30  59

function 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.name; // 返回需要分组的对象 }); return sorted; }; var data=[ {id:1, name:'小明',type:'分类'}, {id:2, name:'大明',type:'分钱'}, {id:3, name:'中明',type:'分兵'}, {id:4, name:'小明',type:'分分'}, {id:5, name:'雷明',type:'分兵'}, {id:6, name:'小明',type:'分兵'}, {id:7, name:'出明',type:'分钱'}, {id:8, name:'中明',type:'分钱'}, {id:9, name:'出明',type:'分分钱'}, {id:10, name:'雷明',type:'分分钱'}, ] sortClass(data)

返回想要的结果

扫码获取 1000+条 前端面试题 收藏以后面试用得上

最新回复(0)