tylkonachwile
tylkonachwile

Reputation: 2267

How to groupby and sum values in typescript

I am trying to get unique user names and their total time, but don't know how to achive this. What I have already done is an array of unique names, but dont know how to get the sum. I think this should be achived by using a structure like dictionary for ex. Dictionary<string,int> but this structure seems to not exists in typescript.

let json = [{"User":"Tom Smith","Hours": 6},{"User":"Mark Zuckerberg","Hours": 8},{"User":"Elon Musk","Hours": 12},{"User":"Tom Smith","Hours": 1},{"User":"Tom Smith","Hours": 1}];

for(var i  = 0; i < json.length; i++)
{
    if(!userNames.find(a => a == json[i].User))
    {
        userNames.push(json[i].User);
    }
}

Result should be:

Upvotes: 3

Views: 5184

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138257

Its called Map:

 const usernames = new Map<string, number>();

 for(const {User, Hours} of json) 
   usernames.set(User, (usernames.get(User) || 0) + Hours);

 console.log([...usernames]);

Upvotes: 8

Related Questions