目前,我正在尝试计算对象数组内的多个出现次数,并将最终计数推入其中。我不想在另一个数组中存储数据。数据应保留在现有数组中。
我想添加计数的数组:
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' }
];
我目前的示例代码从数组中删除/减少元素,因此最终结果不符合要求:
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 }
我会尽力做到以下结果:
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 }
];
希望能指引我正确的方向,非常感谢任何帮助。
谢谢帮忙!期望的解决方案是:
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 }
这段代码并没有太多意义。 - Andy