0

I have an array of objects like this..

[
    {
        _id: 123
    },
    {
        _id: 123
    },
    {
        _id: 321
    }
]

I want to group similar items by _id and also count how many items of each unique _id there are...

[
    {
        _id: 123
        qty: 2
    },
    {
        _id: 321
        qty: 1
    }
]

Whats the best way to do this using javascript?

Serks
  • 333
  • 2
  • 21
  • The posted question does not appear to include [any attempt](https://idownvotedbecau.se/noattempt/) at all to solve the problem. StackOverflow expects you to [try to solve your own problem first](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users), as your attempts help us to better understand what you want. Please edit the question to show what you've tried, so as to illustrate a specific roadblock you're running into a [MCVE]. For more information, please see [ask] and take the [tour]. – CertainPerformance Nov 19 '18 at 23:32
  • 1
    I did try a lot of answers from SO but couldn't get them to work with my particular case. – Serks Nov 19 '18 at 23:51
  • 2
    That's not the same as trying to write code *yourself* - when you post a question, please post the code you're trying to use as well – CertainPerformance Nov 19 '18 at 23:54

1 Answers1

2

You can do this in O(n) time using Array.prototype.reduce() and a Map as the accumulator:

const array = [{'_id':123},{'_id':123},{'_id':321}]
const groups = [...array.reduce(
  (map, { _id }) => map.set(_id, (map.get(_id) || 0) + 1),
  new Map()
)].map(
  ([_id, qty]) => ({ _id, qty })
)

console.log(groups)
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153