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

Posted

技术标签:

【中文标题】在 JS 哈希中按频率获取一个值而不丢失其他键和值【英文标题】:Get one value by frequency in JS hash without losing the other keys and values 【发布时间】:2022-01-14 05:46:56 【问题描述】:

我正在学习 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 来获取国家/地区,但问题是它返回一个没有收入的对象。这是我的代码:

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,还是我走错了路?

【问题讨论】:

【参考方案1】:

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

【讨论】:

以上是关于在 JS 哈希中按频率获取一个值而不丢失其他键和值的主要内容,如果未能解决你的问题,请参考以下文章

在 Perl 中反转哈希的键和值

从数组 ruby​​ 生成哈希键和值

将 perl 正则表达式中的键和值传递给哈希

会话在更改其 ID 时丢失键和值

如何复制粘贴所有格式和值而不使用vb a中的select

perl返回哈希和的键和值