Am not sure what am missing or doing wrong, but I actually want to get a new array containing the properties from one of the objects in the original array and add a property called 'count' to the object that will keep count of the occurrence of a property in the object (example: that property could be title or county, but for my case it's county) and return a new array of objects.
having the array below:
let reports = [
{
county: 'Montserrado',
lat: '1.454354',
lng: '-4.454254',
title: 'Extortion',
city: 'paynesville'
},
{
county: 'Lofa',
lat: '1.454354',
lng: '-4.454254',
title: 'Bribery',
city: 'voinjama'
},
{
county: 'Montserrado',
lat: '1.454354',
lng: '-4.454254',
title: 'Bribery',
city: 'brewerville'
},
{
county: 'Lofa',
lat: '1.454354',
lng: '-4.454254',
title: 'Crynism',
city: 'kolahuun'
},
{
county: 'Grand Bassa',
lat: '1.454354',
lng: '-4.454254',
title: 'Molestation',
city: 'buchanan'
},
{
county: 'Montserrado',
lat: '1.454354',
lng: '-4.454254',
title: 'Bribery',
city: 'paynesville'
},
];
I want to reduce it to an array like this dynamically:
[
{
county: 'Lofa',
lat: '1.454354',
lng: '-4.454254',
title: 'Crynism',
city: 'kolahuun',
count: 2
},
{
county: 'Grand Bassa',
lat: '1.454354',
lng: '-4.454254',
title: 'Molestation',
city: 'buchanan',
count: 1
},
{
county: 'Montserrado',
lat: '1.454354',
lng: '-4.454254',
title: 'Bribery',
city: 'paynesville',
count: 3
},
];
I tried achieving the above with the code block below:
const countyCount = reports
.map(dataItem => dataItem.county) // get all media types
.filter((county, index, array) => array.indexOf(county) === index); // filter out duplicates
const counts = countyCount
.map(countyCount => ({
county: countyCount,
count: reports.filter(item => item.county === countyCount).length
}));
but am getting the below result, which is not what I want
[
{county: 'Montserrado', count: 3},
{county: 'Grand Bassa', count: 1},
{county: 'Lofa', count 2}
]