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个参数:

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方法的参数接受数组也接受具体的值

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

  1. JS中数组对象去重

    JS数组去重 JS中对数组去重最好不要用unique方法,该方法主要是对dom节点数组的去重,如果对普通的数组元素去重只会去掉与之相邻的重复元素,也就是如果数组中还有不相邻的重复元素存在,将不会被去掉 ...

  2. 【原】js数组对象去重最简单的方法

    简单的数组去重是比较简单的,方法也特别多,如给下面的数组去重: let arr = [1,2,2,4,9,6,7,5,2,3,5,6,5] 最常用的可以用for循环套for循环,再用splice删除重 ...

  3. js 数组对象去重

    let hash = {}; let config = [ { name: 2, state: true, output: 'Y'}, { name: 3, state: true, output: ...

  4. 数组对象去重 reduce()

    let log = console.log.bind(console); let person = [ {id: 0, name: "小明"}, {id: 1, name: &qu ...

  5. js中数组对象去重的方法

    var arr = [{ key: '01', value: '乐乐' }, { key: '02', value: '博博' }, { key: '03', value: '淘淘' },{ key: ...

  6. js遍历数组对象和非数组对象

    //---------for用来遍历数组对象 var i,myArr = ["a","b","c"]; ; i < myArr.len ...

  7. js数组对象去重

    转: https://www.cnblogs.com/gaoht/p/9850449.html 在数组对象中去掉重复的对象: export function deteleObject(obj) { v ...

  8. js数组的操作及数组与字符串的相互转化

    数组与字符串的相互转化 <script type="text/javascript">var obj="new1abcdefg".replace(/ ...

  9. JS中集合对象(Array、Map、Set)及类数组对象的使用与对比

    原文地址 在使用js编程的时候,常常会用到集合对象,集合对象其实是一种泛型,在js中没有明确的规定其内元素的类型,但在强类型语言譬如Java中泛型强制要求指定类型. ES6引入了iterable类型, ...

随机推荐

  1. redis GEO地理位置命令介绍

    GEOADD keylongitude latitude member [longitude latitude member ...] Available since 3.2.0. Time comp ...

  2. layui 文件上传加进度条

    1.页面 <div class="layui-row layui-col-space5"> <div class="layui-form-item&qu ...

  3. 在PCL中如何实现点云压缩(1)

    点云由庞大的数据集组成,这些数据集通过距离.颜色.法线等附加信息来描述空间三维点.此外,点云能以非常高的速率被创建出来,因此需要占用相当大的存储资源,一旦点云需要存储或者通过速率受限制的通信信道进行传 ...

  4. 关于 char 和 unsigned char 的区别

    首先卖个关子: 为什么网络编程中的字符定义一般都为无符号的字符?   char buf[16] = {0}; unsigned char ubuf[16] = { 0 };   上面两个定义的区别是: ...

  5. Netty 线程模型与Reactor 模式

    前言 Netty 的线程模型是基于NIO的Selector 构建的,使用了异步驱动的Reactor 模式来构建的线程模型,可以很好的支持成百上千的 SocketChannel 连接.由于 READ/W ...

  6. C# 写 LeetCode easy #20 Valid Parentheses

    20.Valid Parentheses Given a string containing just the characters '(', ')', '{', '}', '[' and ']', ...

  7. 微信小程序iPhone X空白兼容

    开局一张图…… 看看这空白的地方多丑 ~ 接下来就是见证奇迹的时刻(上代码) //app.js App({ onLaunch: function (ops) { if (ops.scene == 10 ...

  8. hortonworks docker 安装

    1. 下载并解压安装脚本:  Hortonworks Data Platform (HDP) for Docker 2. 进入到解压后的目录,运行下面的命令,{HDPversion} 需要替换成相应目 ...

  9. jsp内置对象request的使用方法

    <%@page import="java.text.SimpleDateFormat"%> <%@page import="java.util.Date ...

  10. > Task :app:transformDexArchiveWithExternalLibsDexMergerForDebug FAILED

    > Task :app:transformDexArchiveWithExternalLibsDexMergerForDebug FAILED D8: Cannot fit requested ...