在 JS hash 中按频率获取一个值而不丢失其他键和值

Get one value by frequency in JS hash without losing the other keys and values

我正在学习 Javascript 我有这样的用户散列:

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"}]

我想获得一个键(国家)的频率以及两个最频繁的国家的另一个键(收入)的总和。我试过 .reduce 来获取国家,但问题是它 returns 是一个没有收入的对象。这是我的代码:

const usersByCountry = users.reduce((c, u) => {
  c[u.country] = c[u.country] + 1 || 1;
  return c;
}, {});

这是输出:

Object { "Colombia": 2, "Germany": 3, "United States": 1 }

是否有可能为此利用 .reduce 还是我走错路了?

您可以将所有必需的属性添加到 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);