Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How total an array of items?

Tags:

javascript

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?

like image 575
bier hier Avatar asked Mar 05 '23 06:03

bier hier


1 Answers

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);
like image 126
CertainPerformance Avatar answered Mar 15 '23 22:03

CertainPerformance