reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
reduce() 可以作为一个高阶函数,用于函数的 compose。
语法
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)| 参数 | 描述 | 
|---|---|
| total | 必需。初始值, 或者计算结束后的返回值。 | 
| currentValue | 必需。当前元素 | 
| currentIndex | 可选。当前元素的索引 | 
| arr | 可选。当前元素所属的数组对象。 | 
找最大值
// 找最大值
const result = [1,2,3,3,2,1,6,5].reduce((x,y) => Math.max(x,y));
// 打印结果
console.log(result); // 6数组去重
// 去重
const result = [1,2,3,3,2,1,6,5].reduce((x,y) => {
    // 检测是否存在 
    if(x.indexOf(y) === -1){
        x.push(y);
    }
    return x;
},[]);
// 打印结果
console.log(result); // [ 1, 2, 3, 6, 5 ]数组归类
首先准备一个数组,然后开始使用reduce方法
// 数组
const dataList = [
    {name:'武器',value:'木剑'},{name:'防具',value:'锁子甲'},
    {name:'武器',value:'铁剑'},{name:'消耗品',value:'苹果'},
    {name:'消耗品',value:'西瓜'}
];
// 归类
const resultObj = dataList.reduce((x,y) => {
    const { name } = y;
    if(!x[name]){
        x[name] = [];
    }
    x[name].push(y.value);
    return x;
},{});
// 打印结果
console.log(resultObj); // 拿到的结果{ '武器': [ '木剑', '铁剑' ], '防具': [ '锁子甲' ], '消耗品': [ '苹果', '西瓜' ] }字符串反转
// 字符串
const str = 'hello word';
// 先转成数组 然后反转
const resultStr = Array.from(str).reduce((x,y) => {
    return `${y}${x}`
},'');
// 打印结果
console.log(resultStr); // drow olleh 
                            