2631.分组
链接:2631.分组
难度:Medium
标签:
简介:请你编写一段可应用于所有数组的代码,使任何数组调用 array. groupBy(fn) 方法时,它返回对该数组 分组后 的结果。
题解 1 - typescript
- 编辑时间:2023-04-24
- 执行用时:132ms
- 内存消耗:62.6MB
- 编程语言:typescript
- 解法介绍:遍历。
declare global {
interface Array<T> {
groupBy(fn: (item: T) => string): Record<string, T[]>;
}
}
Array.prototype.groupBy = function (fn) {
const o: Record<string, any> = {};
this.forEach(item => {
let arr = o[fn(item)];
if (!arr) arr = o[fn(item)] = [];
arr.push(item);
});
return o;
};