I have an array of objects:
const fruits = [{
type: oranges,
amount: 10
},
{
type: apples,
amount: 0,
}, {
type: oranges,
amount: 5
}
]
I need to do the following:
- sum up the fruits, if they're the same (f.ex. sum up oranges: {type: oranges, amount: 15})
- add a new key-value pair to object, depending on how many times it is present in the array (f.ex. oranges are present two times: {types: oranges, amount: 15, count: 2} and apples are present one time {types: apples, amount: 0, count: 1} )
So my goal is to have something like this:
const fruits = [{
type: oranges,
amount: 15,
count: 2
},
{
type: apples,
amount: 0,
count: 1
}
]
I found out that the reduce method is a good way to achieve this. I'm working with the following code (this should sum up the amount), but no matter what I try I don't get the result. I just get a new key-value {..., marks: NaN} - so maybe there's a better approach:
const fruits = [{
type: "oranges",
amount: 10
},
{
type: "apples",
amount: 0,
}, {
type: "oranges",
amount: 5
}
]
const endresult = Object.values(fruits.reduce((value, object) => {
if (value[object.type]) {
['marks'].forEach(key => value[object.type][key] = value[object.type][key] + object[key]);
} else {
value[object.type] = { ...object
};
}
return value;
}, {}));
console.log(endresult)
I'm not sure what I'm doing wrong and how can I add the new key-value pair to count the times the object is present in the array? Could someone point me in the right direction? Thanks!
undefined + 5 == NaN