SkinnyGeek1010
SkinnyGeek1010

Reputation: 536

How can I count all dupe values in a JSON collection?

I would like to count all the companies in the following JSON string. I was first planning on doing it manually with loops but it seems like this is a good chance for me to learn to use map/reduce... How can return something that returns {company: 2}?

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

Upvotes: 1

Views: 39

Answers (1)

thefourtheye
thefourtheye

Reputation: 239573

If you want to get the number of unique company names, then

  1. use _.pluck to get the company attribute out of the list of company objects

  2. Find the unique values out of them with _.uniq, which will return an array.

  3. Compose a new object with the key `com

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

Upvotes: 2

Related Questions