I have an array as follow:
const myArray = [
{
name: 'banana',
quotas: [
{
title: 'innerBanana1',
percent: 0.3
},
{
title: 'innerBanana2',
percent: 0.4
}
]
},
{
name: 'apple',
quotas: [
{
title: 'innerApple1',
percent: 0.6
},
{
title: 'innerApple2',
percent: 0.2
}
]
}
]
I would like to sum all the percent in the quotas array only if they belong to the same external object (aka: the name is the same).
Expected Result
finalArray = [
{ name: 'banana', percent: 0.7 },
{ name: 'apple', percent: 0.8 }
]
I tried
const sum = quotaGroups
.map(quotaGroup => quotaGroup.quotas)
.reduce((accumulator, groupedQuota) => {
return accumulator + groupedQuota[0].percent
})
But it clearly does not work. I am missing the link on how to sum only the quotas
of the inner object if the name
is the same
You needed to do the reduce inside the map, otherwise the names were getting lost, and the accumulator was trying to concatenate strings, not total up a number.
const myArray = [ { name: 'banana', quotas: [{title: 'innerBanana1', percent: 0.3}, {title: 'innerBanana2', percent: 0.4}] }, { name: 'apple', quotas: [{title: 'innerApple1', percent: 0.6}, {title: 'innerApple2', percent: 0.2}] } ] const sum = myArray.map(quotaGroup => ({ name: quotaGroup.name, percent: quotaGroup.quotas.reduce((acc, item) => acc + item.percent, 0) })) console.log(sum)
Use map
and reduce
const sum = (arr) => arr.map(({ quotas, name }) => ({ name, percent: quotas.reduce((sum, { percent }) => sum + percent, 0), })); const myArray = [ { name: "banana", quotas: [ { title: "innerBanana1", percent: 0.3, }, { title: "innerBanana2", percent: 0.4, }, ], }, { name: "apple", quotas: [ { title: "innerApple1", percent: 0.6, }, { title: "innerApple2", percent: 0.2, }, ], }, ]; console.log(sum(myArray));
Here is what you want:
const myArray = [ { name: 'banana', quotas: [ { title: 'innerBanana1', percent: 0.3 }, { title: 'innerBanana2', percent: 0.4 } ] }, { name: 'apple', quotas: [ { title: 'innerApple1', percent: 0.6 }, { title: 'innerApple2', percent: 0.2 } ] } ]; console.log(myArray.map(({ name, quotas }) => { return { name, percent: quotas.reduce((a, { percent }) => a + percent, 0) } }));
Use combination of map
and reduce
as below
const finalArray = myArray.map(item => ({
name: item.name,
percent: item.quotas.reduce((acc, cur) => acc + cur.percent, 0)
}));
let finalArray = myArray.map(item => {
let percent = 0;
item.quotas.forEach(function (obj) {
percent += obj.percent
});
return {
name: item.name,
percent: percent
}
})
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.