g2601_2700.s2631_group_by.solution.ts Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
// #Medium #2023_08_31_Time_101_ms_(99.50%)_Space_63.8_MB_(87.11%)
declare global {
interface Array {
groupBy(fn: (item: T) => string): Record
}
}
Array.prototype.groupBy = function (fn: (item: T) => string) { //NOSONAR
const returnObject: Record = {}
for (const item of this) {
const key = fn(item)
if (key in returnObject) {
returnObject[key].push(item)
} else {
returnObject[key] = [item]
}
}
return returnObject
}
/*
* [1,2,3].groupBy(String) // {"1":[1],"2":[2],"3":[3]}
*/
export {}