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

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs