Get count of same values in array of object

Suppose I have an array of object:

const apple = [{"bookName" :'Harry Pottar',part:"1"},{"bookName" :'Harry Pottar',part:"2"},
               {"bookName": 'LOTR',part:"1"},{"bookName": 'LOTR',part:"2"},{"bookName": 'LOTR',part:"3"}]

I want to get count of all common values along with the value name as :

   Expected O/P : [{"Harry Pottar":2},{"LOTR":3"}]

For this I tried as:

const id = "Harry Pottar";
const count = array.reduce((acc, cur) => cur.bookName === id ? ++acc : acc, 0);

As this gives the count, by this I can get count for each bookName. But how can I achieve my expected O/P scenario.

If anyone needs any further information please do let me know.

Answer

Good to see you know about .reduce! You’re pretty close, just need to save the result to a hashmap (plain object in JS).

const array = [{"bookName" :'Harry Pottar',part:"1"},{"bookName" :'Harry Pottar',part:"2"},{"bookName": 'LOTR',part:"1"},{"bookName": 'LOTR',part:"2"},{"bookName": 'LOTR',part:"3"}]

const result = array.reduce((acc, item) => {
  const key = item.bookName
  if (!acc.hasOwnProperty(key)) {
    acc[key] = 0
  }
  acc[key] += 1
  return acc
}, {})

// not sure why you want the result to be multiple objects. But here you go:

const output = Object.entries(result).map(([key, value])=> ({ [key]: value }))