Skip to main content

2631. Group By

https://leetcode.com/problems/group-by

Javascript

Array.prototype.groupBy = function(fn) {
const groups = {}
this.forEach((value) => {
const key = fn(value)
if (!groups.hasOwnProperty(key)) {
groups[key] = []
}
groups[key].push(value)
})
return groups
};

Typescript

declare global {
interface Array<T> {
groupBy(fn: (item: T) => string): Record<string, T[]>
}
}

Array.prototype.groupBy = function(fn) {
const groups = {}
this.forEach((value) => {
const key = fn(value)
if (!groups.hasOwnProperty(key)) {
groups[key] = []
}
groups[key].push(value)
})
return groups
}