// arr.reduce(
//     callback(accumulator, currentValue[, currentIndex[, array]])
//     [, initialValue]
// )

const data1 = [1, 2, 3, 4, 5];
// 没有使用初始值，则 sum 被初始为 1，cur从2开始, ..., ...
let rst1 = data1.reduce((sum, cur) => {
    return sum += cur
})
console.log(rst1)

const data2 = [1, 2, 3, 4, 5];
// 为初始值【1】，则temp被初始为【1】，cur从1开始, ..., ...
let rst2 = data2.reduce((temp, cur) => {
    return temp *= cur
}, 1)
console.log(rst2);

const fruits = ['apple', 'banana', 'apple', 'banana', 'apple'];
const rst3 = fruits.reduce((acc, cur) => {
    if (!acc[cur])
        acc[cur] = 1;
    else
        acc[cur]++;
    return acc;
}, {});
console.log(rst3);

const people = [
    { name: 'zs', age: 25 },
    { name: 'ls', age: 30 },
    { name: 'ww', age: 25 },
    { name: 'sb', age: 30 }
];
// 按年龄进行汇总，acc初始为{}，cur从zs这条数据开始
const rst4 = people.reduce((acc, cur) => {
    const age = cur.age;
    if (!acc[age])
        acc[age] = [];
    acc[age].push(cur);
    return acc;
}, {});
console.log(rst4);

/*
# node reduce.js 
15
120
{ apple: 3, banana: 2 }
{
  '25': [ { name: 'zs', age: 25 }, { name: 'ww', age: 25 } ],
  '30': [ { name: 'ls', age: 30 }, { name: 'sb', age: 30 } ]
}
*/
