All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g2601_2700.s2631_group_by.solution.ts Maven / Gradle / Ivy

There is a newer version: 1.35
Show newest version
// #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 {}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy