簡體   English   中英

如何計算對象數組中屬性的重復次數?

[英]How to count the number of repetitions of properties in an array of objects?

我需要計算每個 object 在數組中按 id 重復的次數,並創建新數組,該數組將具有 object 的“id”之類的值,數組中的重復次數為“count”。 我嘗試使用reduce,但我認為使用錯誤。 嘗試找到答案,但沒有找到用對象創建新數組的變體。

// Array which I have

[
    { name: 'One', id: 3 },
    { name: 'Two', id: 1 },
    { name: 'Three', id: 2 },
    { name: 'Four', id: 1 }
]

// Array which I need to create

[
    { id: 3, count: 1 },
    { id: 1, count: 2 },
    { id: 2, count: 1 },
]

//I have try this code, but it return array with counts [1, 2, 1]

const results = Object.values(arr.reduce((acc, { id }) => {
 acc[id] = (acc[id] || 0) + 1;
 return acc;
}, {}));

謝謝!

你非常接近 - 你的reduce代碼是正確的,但是你需要map你想要的 object 結構的條目:

 const input = [ { name: 'One', id: 3 }, { name: 'Two', id: 1 }, { name: 'Three', id: 2 }, { name: 'Four', id: 1 } ] const result = Object.entries(input.reduce((acc, { id }) => { acc[id] = (acc[id] || 0) + 1; return acc; }, {})).map( ([k,v]) => ({id: parseInt(k,10), count:v})); console.log(result);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM