es6 unique array of objects with set

前端 未结 3 1347
傲寒
傲寒 2020-12-11 15:21

I came across this example for creating unique arrays with es6

[ ...new Set(array) ]

Which seems to work fine until I tried it with an arra

相关标签:
3条回答
  • 2020-12-11 15:42

    Why is that ?

    As per documentation

    The Set object lets you store unique values of any type, whether primitive values or object references.

    Now reference for each of those arrays inside that Set constructor will be different so they are not considered to be a unique value by the constructor.

    0 讨论(0)
  • 2020-12-11 15:52

    This will work:

    let objectReference = {id:123,value:'test'}
    let uniqueArray = [...new Set([objectReference, objectReference])]
    
    >> [{id:123,value:'test'}]
    

    What you're doing:

    let objRef1 = {id:123,value:'test'} // creates a reference to a location in memory
    let objRef2 = {id:123,value:'test'} // creates a new reference to a different place in memory
    
    let uniqueArray = [...new Set([objRef1, objRef2])]
    
    >> [{id:123,value:'test'},{id:123,value:'test'}]
    
    0 讨论(0)
  • 2020-12-11 15:53

    you can try to do

    uniqueArray = a => [...new Set(a.map(o => JSON.stringify(o)))].map(s => JSON.parse(s))
    

    I know its ugly as hell but in most cases works apart from where you have new Date() in your object param then that on stringify be converted to ISO string.

    so then do

    let arr = [{id:1},{id:1},{id:2}];
    uniqueArray(arr) //[{id:1},{id:2}]
    
    0 讨论(0)
提交回复
热议问题