纪录一下刚学会的数组对象的分组
type Person = {
id: number
name: string
age: number
}
onMounted(() => {
let personList: Person[] = [
{ id: 1, name: "John", age: 12 },
{ id: 3, name: "Any", age: 32 },
{ id: 1, name: "Anna", age: 43 }
]
let groups = groupBy(personList, x => x.id, x => x.name)
console.log(groups); //输出结果见下图
})
/**
* 分组
*
* @template T
* @param {T[]} arr
* @param {(x: T) => T[keyof T]} key
* @param {((x: T) => T[keyof T])} [value]
* @return {*}
*/
function groupBy<T>(arr: T[], key: (x: T) => T[keyof T], value?: ((x: T) => T[keyof T])) {
let ret = new Map()
arr.forEach(v => {
let keySelector = key(v)
let valueSelector = value ? value(v) : v
if (ret.has(keySelector)) {
ret.get(keySelector).push(valueSelector)
} else {
ret.set(keySelector, [valueSelector])
}
})
return ret
}