reduce()用法

reduce(cur, next, index, arr):cur代表当前返回的值或初始值,next代表当前正在处理的元素,index标识当前处理元素的索引,arr表示原数组。

reduce()用法:

1,累加器

let arr = [3,5,7,8.10];
let sum =  arr.reduce((cur, next) => {
	return  cur + next;
}, 0) // 返回数组总和

2,去重(去重数据)

let arr = [3,3,5,2,10];
 let arr1 = arr.reduce((cur,next) => {
	cur.indexOf(next) === -1 && cur.push(next);
	return cur;
}, [])

高级用法:
1)去重数组中相同属性的数据,并添加该属性的值到新数组

let offerArr = [{name:'Amy',age: 20},{name:'Tom',age:21},{name:'Rose',age:22},{name:'Tom',age:23}];
let obj = {};
let newArr = offerArr.reduce((cur, next) => {
	obj[next.name] ? '' : obj[next.name] = true && cur.push({offerName:obj[next.name]})
	return cur
}, []) // ['Amy', 'Tom', 'Rose']

2)去重数组中相同属性的数据,并添加该数据到新数组

let newArr2 = offerArr.reduce((cur, next) => {
	obj[next.name] ? '' : obj[next.name] = true && cur.push(next)
	return cur
}, []) // [{name:'Amy',age: 20},{name:'Tom',age:21},{name:'Rose',age:22}]

你可能感兴趣的:(reduce()用法)