利用reduce来求一个由数字组成的数组的和是很简单的:
const arr = [1, 2, 3, 4, 5];
let res = arr.reduce((total, num) => total + num);
那么当数组比较复杂时如何优雅求和?
const arr = [
{name: 'a', val: 1},
{name: 'b', val: 2},
{name: 'c', val: 3},
{name: 'd', val: 4},
{name: 'e', val: 5}
];
思路是先利用map把比较复杂的数组变成简单的数组然后再求和
let res = arr.map(item => item.val).reduce((total, num) => total + num);