简体   繁体   中英

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

I need to count how much each object repeats by id in array and create new array which will have values like 'id' of object and number of repeats in array as 'count'. I try to use reduce but I think use it wrong. Try to find answer but didn't find variant with creating new array with objects.

// 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;
}, {}));

Thank you!

You were very close - your reduce code was spot on, but you then need to map the entries to the object structure you wanted:

 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM