An array of objects to re-reduce ()

 1 let log = console.log.bind(console);
 2 let person = [
 3      {id: 0, name: "小明"},
 4      {id: 1, name: "小张"},
 5      {id: 2, name: "小李"},
 6      {id: 3, name: "小孙"},
 7      {id: 1, name: "小周"},
 8      {id: 2, name: "小陈"},   
 9 ];
10 
11 let obj = {};
12 
13 person = person.reduce((cur,next) => {
14     obj[next.id] ? "" : obj[next.id] = true &&cur.push (Next);
 15      return cur;
 16 }, []) // Set default type array cur, and the initial value is an empty array 
. 17 log (Person);

After printing person, we can get an array of de-duplicated.

Of course, redecu () in addition to and accumulated weights, there are many features, such as multi-dimensional arrays may be flat -

var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {
    return a.concat(b);
}, []); // [0,1,2,3,4,5]

 

In fact, for an array of objects, the traditional method to do anything heavy, as forEach (), filter () and other iterative method not so that; really do go heavy elegance, is a new method ES5 increase --reduce ( )

reduce () method takes a callback function as the first argument, and the callback function accepts four parameters, namely:

 

1.previousValue => initial value or a correction value is superimposed on the function;

2. currentValue => The callback (cycle) the value to be executed;

3. index => "currentValue" index value;

4. arr => array itself;

 reduce () method returns the last call to the callback function's return value;

And then tell the outside question, referred to the weight, many people will think ES6 the Set; but according to my experiments, Set or go for the basic types of heavy, if Set each item is an object, it is not going to heavy, j if any object is exactly the same -

 

 
the let ARR = new new the Set ([ 
    {ID: 0, name: "Bob"}, 
    {ID: 0, name: "Bob"}, 
    {ID: 0, name: "Bob"}, 
    {ID: 0, name: "Bob"}       
]); 
the console.log ([... ARR]); // this is still an object 4

 

Guess you like

Origin www.cnblogs.com/ajaxlu/p/11411913.html