DEV Community

Jen C.
Jen C.

Posted on

LeetCode - Solution for 2631. Group By

My approach

Define the return variable result and its type. Since the array can be any data type of an object array, make the data type of the Record's property values to be typeof this[]:

let result: Record<string, typeof this[]> = {};
Enter fullscreen mode Exit fullscreen mode

Get the Array object using keyword this:

console.log(this);
Enter fullscreen mode Exit fullscreen mode

Iterate over the object array, calling the function fn and pass the object element to get the object property as key.

fn(ele)
Enter fullscreen mode Exit fullscreen mode

Check each element of the array, and if the key exists in the record result, push that element into the property values of result (the array with type typeof this):

if(result[fn(ele)]) result[fn(ele)].push(ele);
Enter fullscreen mode Exit fullscreen mode

If the key does not exist in the record "results", a new array is initialized with that element:

else result[fn(ele)] = [ele];
Enter fullscreen mode Exit fullscreen mode

Also on the gitHub repo


...

Array.prototype.groupBy = function(fn) {
    let result: Record<string, typeof this[]> = {};    
    // console.log(this);

    this.forEach(
        ele => {
            if(result[fn(ele)]) result[fn(ele)].push(ele);            
            else result[fn(ele)] = [ele];
        }
    );
    return result;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)