一组物品的总数是多少?

时间:2019-03-31 22:21:33

标签: javascript

我具有以下数组结构:

let val = [
  {
    currentYear:'11',
    lastYear:'12',
    name:'Bert',
    type:'+'
  },
  {
    currentYear:'2',
    lastYear:'4',
    name:'Ed',
    type:'-'
  }
]

我试图根据类型总计数字字段。当类型为“ +”时,我添加项目,而“-”为减法。函数的结果应为:

{
  currentYear:9,
  lastYear:8
}

到目前为止,我已经提出了这个建议:

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;
}, {});

我只是不知道如何根据类型进行加减?

1 个答案:

答案 0 :(得分:7)

您可以使用reduce并将currentYearlastYear乘以(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);