Js之reduce()用法

reduce() 方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。

语法:

arr.reduce(callback, [initialValue])

即:

arr.reduce((previousValue, currentValue, index, arr), [initialValue])
callback (执行数组中每个值的函数,包含四个参数)

    1、previousValue (上一次调用回调返回的值,或者是提供的初始值initialValue)
    2、currentValue (数组中当前被处理的元素)
    3、index (当前元素在数组中的索引)
    4、array (调用 reduce 的源数组)

initialValue (作为第一次调用 callback 的第一个参数)

用法示例:

1、加法、乘法...

const arr = [1, 2, 3, 4]
arr.reduce((x, y) => x + y)
arr.reduce((x, y) => x * y)

2、计算数组中每个元素出现的次数

const arr1 = ['aa', 'bb', 'cc', 'dd', 'ee', 'aa', 'bb'];

let arrNum = arr1.reduce((pre, cur) => {
  if (cur in pre) {
    pre[cur] += 1;
  } else {
    pre[cur] = 1;
  }
  return pre;
}, {});

console.warn(arrNum);

 

3、数组去重

const arr2 = [1, 2, 3, 4, 4, 5, 1];

arr2.reduce((pre, cur) => {
  if (!pre.includes(cur)) {  
    return pre.concat(cur); // 同 return [...pre, cur];
  }
  return pre;
}, []);

 

 tip:也可以采用[... new Set(arr2)]  <=>  Array.from(new Set(arr2))

4、将二维数组转化为一维

let arr = [[0, 1], [2, 3], [4, 5]]

let newArr = arr.reduce((pre,cur)=>{
    return pre.concat(cur)
},[])

console.warn(newArr);

tip: 也可以采用 arr.flat() 或者 arr.flat(1)

5、对象里的属性求和

const arr5 = [{ label: '1', value: 1}, { label: '2', value: 2}, { label: '3', value: 3}];

arr5.reduce(((x, y) => x + y.value), 0);

实际应用: 

找到图层组中图层zindex最大的图层,设置当前图层的zindex高于最大图层。

const maxLayers = this.vecWktLayers.reduce((x, y) => x.getZIndex() >= y.getZIndex() ? x : y , curVecWKTLayer);

curVecWKTLayer.setZIndex(maxLayers.getZIndex() + 1);

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值