1、通用分组
function groupBy(list, fun) {
let obj = {}
let prop = fun
if (typeof fun == "string") {
fun = (item) => item[prop];
}
for (const item of list) {
const key = fun(item);
if (!obj[key]) {
obj[key] = [];
}
obj[key].push(item);
}
return obj;
}
let arr = [{name: "李白", age: 20}, {name: "王勃", age: 20}, {name: "李煜", age: 30}]
// 1、传入字符串
groupBy(arr, "name")
// 2、传入函数
groupBy(arr, item => item.age)
groupBy(arr, item => item.name.substring(0, 1))