Q:

filter array for unique items with item count

Helo,
I am using the following code to return a unique list of categories.
  stadium_cats: function () {
    let stadiums =[
        {"name":"Elland road","category":"football","country":"England"},
        {"name":"Principality stadiums","category":"rugby","country":"Wales"},
        {"name":"Twickenham","category":"rugby","country":"England"},
        {"name":"Eden Park","category":"rugby","country":"New Zealand"}
    ];

    var categories  = stadiums.map(function(obj) {return obj.category});
    categories = categories.filter(function(v,i) {return categories.indexOf(v) == i; });
    return categories;
  }

When I run the above I get an array of unique stadium.category values.
Could someone help me extend it, so that instead of an array returned I get an array of objects as follows:
[{"name":"football","count":"1"}{"name":"rugby","count":"3"}]

I would like both the name and how many times it was featured?
Is this at all possible?
Many thanks,
Dave

A:

Just one line with ES6:

let stadiums = [{ name: 'Elland road', category: 'football', country: 'England' }, { name: 'Principality stadiums', category: 'rugby', country: 'Wales' }, { name: 'Twickenham', category: 'rugby', country: 'England' }, { name: 'Eden Park', category: 'rugby', country: 'New Zealand' }];
let result = [...new Set(stadiums.map(s => s.category))].map(c => ({ name: c, count: stadiums.filter(s => s.category === c).length }));

console.log(result);

