js技巧-使用reduce实现更简洁的数组对象去重和数组扁平化

Array.prototype.reduce()方法介绍:
感性认识reduce累加器:
const arr = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
console.log(arr.reduce(reducer)); //10,即1 + 2 + 3 + 4。
console.log(arr.reduce(reducer, 6));//16,即6 + 1 + 2 + 3 + 4。

你可以通过打印reducer的两个参数,从而直观的感受到,第二个参数currentValue是当前的元素,而第一个参数accumulator总是返回每一次执行reducer函数的返回值,如此一次次累加起来。

reduce方法接收两个参数:

reduce(callback,initialValue)

callback(accumulator,currentValue, index,arr) : 执行于每个数组元素的函数;
initialValue : 传给callback的初始值。

更详细的讲,callback就是由你提供的reducer函数,调用reduce()方法的数组中的每一个元素都将执行你提供的reducer函数,最终汇总为单个返回值

reducer函数(callback)接受4个参数:

1204317-20190413010338308-1456138788.png

1. reduce()实现数组对象去重:

简单的数组去重,我们可以通过把数组转换为ES6提供的新数据结构Set实现。
然而在实际业务上,我们经常需要处理后台返回的json格式的数组对象进行去重。
比如:

const arr = [{
  id: 1,
  phone: 1880001,
  name: 'wang',
  },{
  id: 2,
  phone: 1880002,
  name: 'li',
  },{
  id: 3,
  phone: 1880001,
  name: 'wang',
}]

我们会需要去掉电话号码重复的元素,这时候就需要使用hash检测方法:

const unique= arr =>{
  let hash = {};
    return arr.reduce((item, next) => {
      hash[next. phone]? '': hash[next.phone] = true && item.push(next);
        return item
    }, []);
}
unique(arr) 
/* [{
  id: 1,
  phone: 1880001,
  name: 'wang',
  },{
  id: 2,
  phone: 1880002,
  name: 'li',
  }] */
2. reduce()实现数组扁平化:
const flatten= arr => arr.reduce((item, next) => item.concat( Array.isArray(arr)? flatten(next): next, []));
//concat方法的参数接受数组也接受具体的值

转载于:https://www.cnblogs.com/guoyingjie/p/10699533.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值