I am learning Javascript and I have a hash of users like this:
const users = [{id: 1, firstName: "Jose", revenue: 3700, country: "Colombia"}, {id: 2, firstName: "Rodney", revenue: 9100, country: "Germany"}, {id: 3, firstName: "Danny", revenue: 0, country: "United States"}, { id: 4, firstName: "Birgit", revenue: 7700, country: "Germany"}, {id: 5, firstName: "Audra", revenue: 0, country: "Germany"},{id: 6, firstName: "Doreatha", revenue: 0, country: "Colombia"}]
and I'd like to get the frequencies of one key (country) as well as the sum of another key (revenue) of the two most frequent countries. I tried .reduce to get the countries, but the trouble is that it returns an object with no revenues. Here is my code:
const usersByCountry = users.reduce((c, u) => {
c[u.country] = c[u.country] + 1 || 1;
return c;
}, {});
And here's the output :
Object { "Colombia": 2, "Germany": 3, "United States": 1 }
Is it even possible to exploit .reduce for this or am I on the wrong track?
You can add all required properties to the accumulator object in reduce:
const users = [{id: 1, firstName: "Jose", revenue: 3700, country: "Colombia"}, {id: 2, firstName: "Rodney", revenue: 9100, country: "Germany"}, {id: 3, firstName: "Danny", revenue: 0, country: "United States"}, { id: 4, firstName: "Birgit", revenue: 7700, country: "Germany"}, {id: 5, firstName: "Audra", revenue: 0, country: "Germany"},{id: 6, firstName: "Doreatha", revenue: 0, country: "Colombia"}]
const usersByCountry = users.reduce((acc, u) => {
acc[u.country] = {
frequency: (acc[u.country]?.frequency ?? 0) + 1,
revenue: (acc[u.country]?.revenue ?? 0) + u.revenue
};
return acc;
}, {});
console.log(usersByCountry);