假設有這樣一個數組:
let person = [ {id: 0, name: "小明"}, {id: 1, name: "小张"}, {id: 2, name: "小李"}, {id: 3, name: "小孙"}, {id: 1, name: "小周"}, {id: 2, name: "小陈"}, ]
我們想去掉數組中id重複的對象,比如同樣id為2的兩個對象——
{id: 2, name: "小李"}和{id: 2, name: "小陈"} (去掉任何一个都可以)
我們該如何去做呢?
事實上,對於數組對象,傳統的去重方法無能為力,至於forEach()、filter()等迭代方法也不好使;真正能做到優雅去重的,是ES5新增加的一個方法-reduce()
reduce()方法接收一個回呼函數作為第一個參數,回呼函數又接受四個參數,分別是:
1. cur => 首個值或與後面的值疊加的結果;
##2. next => 下一個要疊加的值;
#3. index => 索引值;
#4. arr => 陣列本身;
#reduce常用的方法就是不斷疊加陣列中的每一項,並回傳出來;
let log = console.log.bind(console); let arr = [1,2,3,4,5,6]; arr = arr.reduce((cur,next) => { return cur + next; }) log(arr); // 21
let log = console.log.bind(console); let arr = [1,2,3,4,5,6]; arr = arr.reduce((cur,next) => { return cur + next; },0) //指定cur的类型为Number并且初始值为0,当设为1时,最终打印的值为22log(arr); // 21
let log = console.log.bind(console); let person = [ {id: 0, name: "小明"}, {id: 1, name: "小张"}, {id: 2, name: "小李"}, {id: 3, name: "小孙"}, {id: 1, name: "小周"}, {id: 2, name: "小陈"}, ]; let obj = {}; person = person.reduce((cur,next) => { obj[next.id] ? "" : obj[next.id] = true && cur.push(next); return cur; },[]) //设置cur默认类型为数组,并且初始值为空的数组 log(person);
以上是從給數組中的物件去重看js中的reduce()的詳細內容。更多資訊請關注PHP中文網其他相關文章!