Currently I am trying to count multiple occurrences inside an array of objects and push a final counting into it. I do not want to have the data storred in an additional array. The data should stay in the existing one.
The array I'd try to add the count:
var array = [
{ artist: 'metallica', venue: 'olympiastadion' },
{ artist: 'foofighters', venue: 'wuhlheide' },
{ artist: 'metallica', venue: 'columbiahalle' },
{ artist: 'deftones', venue: 'columbiahalle' },
{ artist: 'deichkind', venue: 'wuhlheide' },
{ artist: 'metallica', venue: 'wuhlheide' },
{ artist: 'foofighters', venue: 'trabrennbahn' }
];
My current example code deletes/reduces from the array so the final result is not as desired:
var array = [
{ artist: 'metallica', venue: 'olympiastadion' },
{ artist: 'foofighters', venue: 'wuhlheide' },
{ artist: 'metallica', venue: 'columbiahalle' },
{ artist: 'deftones', venue: 'columbiahalle' },
{ artist: 'deichkind', venue: 'wuhlheide' },
{ artist: 'metallica', venue: 'wuhlheide' },
{ artist: 'foofighters', venue: 'trabrennbahn' }
];
array = Object.values(array.reduce((r, { artist, venue }) => {
r[artist] = r[artist] || { artist, venue, count: 0 };
r[artist].count++;
return r;
}, {}));
console.log(array);
Which logs:
{ artist: 'metallica', venue: 'olympiastadion', count: 3 },
{ artist: 'foofighters', venue: 'wuhlheide', count: 2 },
{ artist: 'deftones', venue: 'columbiahalle', count: 1 },
{ artist: 'deichkind', venue: 'wuhlheide', count: 1 }
I am trying to achieve the result as:
var array = [
{ artist: 'metallica', venue: 'olympiastadion', count: 3 },
{ artist: 'foofighters', venue: 'wuhlheide', count: 2 },
{ artist: 'metallica', venue: 'columbiahalle', count: 3 },
{ artist: 'deftones', venue: 'columbiahalle', count: 1 },
{ artist: 'deichkind', venue: 'wuhlheide', count: 1 },
{ artist: 'metallica', venue: 'wuhlheide', count: 3 },
{ artist: 'foofighters', venue: 'trabrennbahn', count: 2 }
];
Any help is appreciated to point me in the right direction.
Thank you for helping! The desired solution is:
var array = [{ artist: 'metallica', venue: 'olympiastadion' }, { artist: 'foofighters', venue: 'wuhlheide' }, { artist: 'metallica', venue: 'columbiahalle' }, { artist: 'deftones', venue: 'columbiahalle' }, { artist: 'deichkind', venue: 'wuhlheide' }, { artist: 'metallica', venue: 'wuhlheide' }, { artist: 'foofighters', venue: 'trabrennbahn' }],
map = array.reduce(
(map, { artist }) => map.set(artist, (map.get(artist) || 0) + 1),
new Map
),
array = array.map(o => Object.assign({}, o, { count: map.get(o.artist) }));
console.log(array);
{ artist: 'metallica', venue: 'olympiastadion', count: 3 }doesn't really make sense.