Suppose there is such an array:
let person = [ {id: 0, name: "小明"}, {id: 1, name: "小张"}, {id: 2, name: "小李"}, {id: 3, name: "小孙"}, {id: 1, name: "小周"}, {id: 2, name: "小陈"}, ]
We want to remove objects with duplicate IDs in the array, such as two objects with the same ID of 2——
{id: 2, name: "小李"}和{id: 2, name: "小陈"} (去掉任何一个都可以)
How should we do it? ?
In fact, for array objects, traditional deduplication methods are powerless, and iteration methods such as forEach() and filter() are not easy to use; what can really achieve elegant deduplication is the new addition of ES5 A method - reduce()
reduce() method receives a callback function as the first parameter, and the callback function accepts four parameters, namely:
1. cur => The first value or the result of superposition with subsequent values;
2. next => The next value to be superimposed;
##3. index => Index value;
4. arr => The array itself;
The common method of reduce is to continuously superimpose each element in the array. One item and return it;
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);
The above is the detailed content of Revisit reduce() in js from giving objects in arrays. For more information, please follow other related articles on the PHP Chinese website!