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