reduce()的基本用法

一、语法:

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

二、参数:

total 必需。初始值, 或者计算结束后的返回值。
currentValue: 必需。当前元素
currentIndex: 可选。当前元素的索引
arr: 可选。当前元素所属的数组对象。
initialValue: 可选。传递给函数的初始值
其实常用的参数只有两个:total 和 currentValue

三、例子

1.求数组之和

  /*
  求数组之和
  这里面initialValue参数传入的是0,所以total的初始值是0
  currentValue的初始值是数组的第一项,也就是11
  */ 
  var arr = [11,22,33,44];
  var sum = arr.reduce((total, currentValue) => {
    console.log('total',total)
    console.log('currentValue',currentValue)
    return Math.max()
  },0)
  console.log(sum)

打印结果:


reduce的数组求和.png

2.求这个数组的最大值

  /*
  求这个数组的最大值
  这里不传入初始值, total 的初始值就是数组的第一项
  currentValue的初始值是第二项
  Math.max()  返回两个指定的数中带有较大的值的那个数:
  */ 
 var arr2 = [11,33,4,8,10,56,88,3,7,22];
 var max = arr2.reduce((total, currentValue) => {
    return Math.max(total,currentValue)
  })
  console.log(max)  // 打印输出: 88

3.数组去重

  /*
  数组去重
  基本原理:
  1. 第一次传入一个空数组,所以prev = [],相当于初始化一个空数组,所以第一次肯定会push进去的。
  2. 第二项 ‘8’ 传入 prev.indexOf(currentValue) 查找, ===-1的话,也是push进去,没有找到相同的项。
  3. 第三项 ‘3’ 传入 prev.indexOf(currentValue) 查找, !== -1 , 所以prev数组是 不进行push操作。 
  4. 以此类推, 最后将这个初始化数组返回
  */
 var arr3 = [3,8,3,4,6,7,3,4,77,8];
 var newArr = arr3.reduce((prev, currentValue) => {
    prev.indexOf(currentValue) === -1 && prev.push(currentValue);
    return prev;
},[]);
console.log(newArr)  // 打印输出:  [3, 8, 4, 6, 7, 77]

4.字符串,每个字母出现的次数

/*
字符串,每个字母出现的次数
初始化为一个空对象,{}
*/
const str1 = 'abcssxsaw';  // 打印输出:  ['a', 'b', 'c', 's', 's', 'x', 's', 'a', 'w']
console.log(str1.split(''))
const obj = str1.split('').reduce((prev, currentValue) => {
  console.log(prev[currentValue])
  prev[currentValue] ? prev[currentValue]++ : prev[currentValue] = 1;
  return prev
},{})

console.log(obj) // 打印输出: {a: 2, b: 1, c: 1, s: 3, w: 1, x: 1}

打印结果:


reduce查找字符串出现的次数.png

5.数组转对象(这个是我项目中遇到的)
初始化数组:roles


reduce数组转对象.png
const roleNames = roles.reduce((pre, role) => {
      pre[role._id] = role.name
      return pre
    }, {})

打印结果:


实际项目应用.png

6.重构一个数组(将其中一个相同的属性分类)

        let list = [{ szcs: '4', fh: '404', zh: '1', xqmc: '阳光家园'},
            {szcs: '2', fh: '201', zh: '1', xqmc: '阳光家园'},
            { szcs: '4', fh: '401', zh: '1', xqmc: '阳光家园'},
            { szcs: '22', fh: '2202', zh: '1', xqmc: '阳光家园'},
            { szcs: '4', fh: '402', zh: '1', xqmc: '阳光家园'},
            { szcs: '14', fh: '1402', zh: '1', xqmc: '阳光家园'},
            { szcs: '17', fh: '1701', zh: '1', xqmc: '阳光家园'},
            { szcs: '2', fh: '202', zh: '1', xqmc: '阳光家园'},
        ]

        function filterData(data) {
            if (!data) {
                return []
            }
            let currentIndex = -1;
            return data.reduce((prev, next) => {
                currentIndex = prev.findIndex(v => v.szcs == next.szcs)
                if (currentIndex > -1) {
                    prev[currentIndex].houseList.push(next)
                } else {
                    prev.push({
                        szcs: next.szcs,
                        houseList: [next]
                    })
                }
                return prev
            }, [])
        }
        // 调用
        let newData = filterData(list)
        console.log(newData);

打印结果:


微信图片_20220612111545.png

数组成员特性分组(和上面是一样的,从别的网站看到的)

arr: [
        {area: 'GZ', name: '熊大', age: 100},
        {area: 'FS', name: '光头强', age: 30},
        {area: 'GZ', name: '熊二', age: 98},
        {area: 'SZ', name: '吉吉国王', age: 120},
        {area: 'SZ', name: '飞鸟', age: 10},
        {area: 'FS', name: '猴子', age: 90},
        {area: 'GZ', name: '博士', age: 40},
      ]
group(arr = [], key) {
      return key ? arr.reduce((t, v) => (!t[v[key]] && (t[v[key]] = [] ), t[v[key]].push(v), t), {}) : {};
    },

console.log(this.group(this.arr, "area"))

打印结果:


reduce.png

你可能感兴趣的:(reduce()的基本用法)