【问题标题】:How can I count all dupe values in a JSON collection?如何计算 JSON 集合中的所有重复值?
【发布时间】:2014-03-21 07:08:29
【问题描述】:

我想计算以下 JSON 字符串中的所有公司。我最初计划使用循环手动执行此操作,但这似乎是我学习使用 map/reduce 的好机会...如何返回返回 {company: 2} 的内容?

[
  {
    _id: '123',
    company: 'Acme'
  }
  {
    _id: '123',
    company: 'Innatrode'
  }
  {
    _id: '123',
    company: 'Acme'
  }
]

【问题讨论】:

  • 问题不是很清楚。您想要唯一的公司名称的数量吗?

标签: javascript mapreduce underscore.js


【解决方案1】:

如果要获取唯一公司名称的数量,那么

  1. 使用_.pluck 从公司对象列表中获取company 属性

  2. 使用_.uniq从中找出唯一值,这将返回一个数组。

  3. 用 `com 键组成一个新对象

    console.log({company: _.uniq(_.pluck(companies, "company")).length});
    # { company: 2 }
    

【讨论】:

  • 谢谢!这是完美的。
猜你喜欢
  • 2018-04-26
  • 2019-04-20
  • 2022-12-09
  • 2010-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-11
相关资源
最近更新 更多