arr.reduce的数组对象去重
var nums = [
{ label: '123', value: 244 },
{ label: '123', value: 244 },
{ label: 'qwe', value: 244 },
{ label: 'qwe', value: 244 },
{ label: '56', value: 244 },
{ label: '56', value: 244 },
{ label: '56', value: 244 },
{ label: '78', value: 244 },
{ label: '78', value: 244 },
{ label: '78', value: 244 },
]
var temp = {}
nums = nums.reduce((pre,cur)=> {
if(!temp[cur.value]){
pre.push(cur)
temp[cur.value] = true
}
return pre
},[])
console.log(nums);
- pre —— 是上一个函数调用的结果,第一次等于 [ ] (或者undefined)
- cur —— 当前的数组对象。
它们还可以用于数组计算单个值。
let value = arr.reduce(function(accumulator, item, index, array) { // ... }, [initial]);
- accumulator —— 是上一个函数调用的结果,第一次等于 initial(如果提供了 initial 的话)
- item —— 当前的数组元素。
- index —— 当前索引。
- arr —— 数组本身。
应用函数时,上一个函数调用的结果将作为第一个参数传递给下一个函数。
因此,第一个参数本质上是累加器,用于存储所有先前执行的组合结果。最后,它成为 reduce 的结果。
ps: 建议始终指定初始值。
let arr = [1, 2, 3, 4, 5];
let result = arr.reduce((sum, current) => sum + current, 0);
console.log(result); // 15