1

I'm sure this has been answered ad nauseum, but the answers I'm finding are pretty vague/abstract.

Say I have an array of objects:

const tags = [
  {title: 'fiction'},
  {title: 'non-fiction'},
  {title: 'fiction'},
  {title: 'non-fiction'},
  {title: 'non-fiction'},
]

What I'd like to do is put together another array that counts the number of times a particular title occurs in the original array:

const distilled = [
  {fiction: 2},
  {non-fiction: 3}
]

I'm sure I need to loop through the tags array, check e.title against the keys that currently exist in distilled, and if it's there, add to the value, versus if not, add it as an object with a value of 1.

Where I'm stumped is that second step, checking whether an object already exists in distilled with that specific key. It would be easy to use Array.prototype.find() if it was just an array of individual values. But since it's an array of objects, I'm not sure how to check that without looping through distilled again and again for each item in tags and looking for hasOwnKey.

There has to be some way with .map() or .reduce(), right? I'd appreciate any help

R Greenstreet
  • 719
  • 6
  • 21
  • Please visit [help], take [tour] to see what and [ask]. ***[Do some research](https://www.google.com/search?q=javascript+group+count+array+site:stackoverflow.com)***, search for related topics on SO; if you get stuck, post a [mcve] of your attempt, noting input and expected output, preferably in a [Stacksnippet](https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/) – mplungjan Feb 03 '21 at 17:23
  • 1
    @mplungjan Thank you! I completely forgot about the `object[key]` syntax in the second answer of the suggested duplicate. – R Greenstreet Feb 03 '21 at 17:36

0 Answers0