定义和用法

reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
注意: reduce() 对于空数组是不会执行回调函数的。

语法

  1. array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

参数

reduce(对象数组去重) - 图1

数组去重

  1. let person = [
  2. {id: 0, name: "小明"},
  3. {id: 1, name: "小张"},
  4. {id: 2, name: "小李"},
  5. {id: 3, name: "小孙"},
  6. {id: 1, name: "小周"},
  7. {id: 2, name: "小陈"},
  8. ];
  9. let obj = {};
  10. person = person.reduce((total,cur) => {
  11. obj[cur.id] ? "" : obj[cur.id] = true && total.push(cur);
  12. return total;
  13. },[]) //设置total初始值为空数组