I have the following array structure:
let val = [
{
currentYear:'11',
lastYear:'12',
name:'Bert',
type:'+'
},
{
currentYear:'2',
lastYear:'4',
name:'Ed',
type:'-'
}
]
I am trying to total the numbers fields depending on the type. When the type is '+' I add the item and '-' is subtract. The result of the function should then be:
{
currentYear:9,
lastYear:8
}
Sofar I have come up with this:
const sums = val.reduce((acc, item) => {
Object.entries(item)
.filter(([_, v]) => !isNaN(v))
.forEach(([k, v]) => acc[k] = (acc[k] || 0) + Number(v));
return acc;
}, {});
I just cannot figure out how to add or subtract depending on the type?
You could use reduce
and multiply the currentYear
or lastYear
by (type === '+' ? 1 : -1)
:
let val = [{
currentYear: '11',
lastYear: '12',
name: 'Bert',
type: '+'
},
{
currentYear: '2',
lastYear: '4',
name: 'Ed',
type: '-'
}
];
const total = val.reduce((a, { currentYear, lastYear, type }) => {
const mult = type === '+' ? 1 : -1;
a.currentYear += mult * currentYear;
a.lastYear += mult * lastYear;
return a;
}, { currentYear: 0, lastYear: 0});
console.log(total);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With