博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
js技巧-使用reduce实现更简洁的数组对象去重和数组扁平化
阅读量:6910 次
发布时间:2019-06-27

本文共 1388 字,大约阅读时间需要 4 分钟。

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

你可能感兴趣的文章
8 月编程语言排行榜:Python 强势逼近 Java,C 已穷途末路
查看>>
人工智能已经说烂,DuerOS告诉你是如何工作的
查看>>
一盘很大的棋,阿里3年内要招揽200名青年科学家
查看>>
正确面对跨域,别慌
查看>>
关于input的一些问题解决方法分享
查看>>
【译】Effective TensorFlow Chapter8——控制流操作:条件和循环
查看>>
骗子或许比你更了解网络攻防
查看>>
从贝叶斯定理到概率分布:综述概率论基本定义
查看>>
Satoshis Vision大会:‘乱局’之中的Bitcoin Cash
查看>>
前端中的 IoC 理念
查看>>
Android开源框架源码鉴赏:VirtualAPK
查看>>
在 V8 引擎中设置原型(prototypes)
查看>>
源码|并发一枝花之ReentrantLock与AQS(2):lockInterruptibly
查看>>
Lumen 使用 throttle 限制接口访问频率
查看>>
怎样给文件命名才能显得更加专业
查看>>
python多线程
查看>>
原来云数据库也是有思想的...
查看>>
GitHub 项目徽章的添加和设置
查看>>
写给前端新人:前端开发必会的知识点
查看>>
欢乐的票圈重构之旅——RecyclerView的头尾布局增加
查看>>