3 回答

TA貢獻(xiàn)1876條經(jīng)驗(yàn) 獲得超6個(gè)贊
我希望這有幫助
let counterObj = {};
let cars = [
{ id: 1, name: 'Mercedes', year: '2015' },
{ id: 2, name: 'Mercedes', year: '2000' },
{ id: 3, name: 'BMW', year: '2010' },
{ id: 4, name: 'BMW', year: '2004' },
{ id: 5, name: 'Volvo', year: '2012' },
{ id: 6, name: 'Volvo', year: '2014' }
];
for (let item of cars){
counterObj[item.name] = 1 + (counterObj[item.name] || 0)
}
console.log(counterObj);

TA貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超11個(gè)贊
您可以使用其頻率reduce生成地圖。PostId
function mapFrequency(data) {
return data.reduce((map, datum) => {
if (map[datum.postId]) {
map[datum.postId] += 1;
} else {
map[datum.postId] = 1
}
return map;
}, {})
}
此函數(shù)將創(chuàng)建一個(gè)對(duì)象,其鍵為 as postId,值為其頻率。
如果你想在你的樣本中生成一個(gè)數(shù)組,你可以這樣做
const frequencies = mapFrequency(data);
const result = Object.keys(frequencies).map((id) => {
return {
PostId: id,
frequency: frequencies[id]
}
});

TA貢獻(xiàn)2016條經(jīng)驗(yàn) 獲得超9個(gè)贊
使用 reduce,您可以執(zhí)行以下操作:
const na = data.reduce((acc, el) => {
acc[el.postId] = acc[el.postId] ? acc[el.postId] + 1 : 1;
return acc;
}, {});
與@sonEtLumiere 建議的幾乎相同,但與reduce
添加回答
舉報(bào)