0

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!

2
  • 2
    "I try to use reduce but I think use it wrong" Please include your attempt(s) so we can help you understand and solve the problem Commented May 6, 2021 at 9:32
  • Does this answer your question? Counting occurrences of Javascript array Commented May 6, 2021 at 9:37

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.