reduce实现极简化的小工具

1. reduce介绍
reduce() 方法接收一个函数作为累加器(accumulator),数组中的每个值(从左到右)从左到右依次处理。并返回最终的处理值
arr.reduce(callback, init);
reduce 接收两个参数,其中的callback是处理数据的一个回调函数其中接收四个参数,init为处理数据的起始值。

arr.reduce((preResult, curValue, index, arr) => {
	// preResult 是上一次处理的结果值
	// curValue 是本次操作的数组元素
	// index  是本次数组元素的索引
	// arr 是操作数组
}, [] );/* [] 为初始值 */
  • eg-1 数组求和
let items = [1,2,3,4,5]
let addValue = items.reduce( (prev, curv) => {
   return prev += curv 
},0) 
console.log(addValue)  // 15
  • eg-2 对象数组去重
let arr = [ {a:1, id: 1},{b:1, id: 2},{c:3, id: 1},{d:4, id: 4},{e:5, id: 1}] //去掉id重复的 数组元素
const hash = {}  //定义一个hash数组用作去重字典
const result = arr.reduce( (preValue, curValue) => {
  hash[curValue.id] ? "" : (hash[curValue.id] = true && preValue.push(curValue))
  return preValue
},[])
  • eg-3 对象取值方法封装 (防止 a.b.c b为undefined 的时候报错)
let items = {
	"a": {
		"b": {
			"c": {
				"d": {
					"e": {
						"f": 3
					}
				}
			}
		}
	}
}
function $getValue(obj, path){
    if (obj && path) {
        return path.split(".").reduce((preResult, curValue) => {
            if (preResult[curValue]) {
                return preResult[curValue];
            } else {
                return undefined;
            }  
        }, obj);
    } else {
        return obj;
    }
}
let valueF = $getValue(items, 'a.b.c.d.e.f')
console.log(valueF) // 3
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值