ES6 set of data structures and the array of objects map to achieve re simple

Since the set of data structures with es6, the array can be easily implemented to re-line of code, such as the following manner

let arr = [1, 2, 2, 3, 4]
function unique (arr) {
    return [...new Set(arr)]
}
console.log(unique(arr)) // [1, 2, 3, 4]

However, when the item in the array is no longer a simple data type, such as is the object, this method will lead to an error, such as the following results

the let ARR = [ 
    {name: 'A', NUM:. 1 }, 
    {name: 'B', NUM:. 1 }, 
    {name: 'C', NUM:. 1 }, 
    {name: 'D', NUM:. 1 }, 
    {name: 'A', NUM:. 1 }, 
    {name: 'A', NUM:. 1 }, 
    {name: 'A', NUM:. 1 } 
] 
function UNIQUE (ARR) {
     return [... new new the SET (arr)] 
} 
console.log (UNIQUE (arr)) // result of the original array, are interested can try to copy the code

The reason for this is because the object set data structure never considered equal, even if the two empty objects, but also within the range set structure

For these reasons, the use of map structure of the package for a simple way to the weight of the object array, as follows

// ES6 array of objects all of the attributes to re-screened character of each item in the array 
function UNIQUE (arr) { 
    const RES = new new the Map ()
     return arr.filter (Item =>! Res.has (JSON.stringify (Item)) res.set && (the JSON.stringify (Item),. 1 )) 
} 
// for ES6 one-dimensional array of objects to an attribute value of the weight and of a simple data type of the attribute 
function UNIQUE (ARR, Key) { 
    const RES = new new map ()
     return arr.filter ((Item) =>! res.has (Item [Key] + '') && res.set (Item [Key] + '',. 1 )) 
}

Online friends devised a simpler method, mainly out differently understanding of key map data structure, no other differences, as follows

// ES6 array of objects all of the attributes to re-screening of each item in the array of characters 
function unique2 (arr) { 
    const RES = new new the Map ()
     return arr.filter (Item =>! Res.has (Item) && res.set ( Item,. 1 )) 
}

Actually I tried it, and found no effect of weight to play, do not know what the specific reason, my understanding is that when an object with each item refers to algebraic group when, item stored is a pointer to the object, that address on the stack, not the object itself, so every item of address is not the same, even though they all point to the same data heap, so the map does not assume that every item equal, of course, would not achieve the effect of de-duplication . If there are more accurate and in-depth understanding welcome to discuss Kazakhstan

Guess you like

Origin www.cnblogs.com/p-l-u-m/p/10950774.html