How can I get a unique array based on object property using underscore

前端 未结 8 1252
遇见更好的自我
遇见更好的自我 2020-12-29 18:30

I have an array of objects and I want to get a new array from it that is unique based only on a single property, is there a simple way to achieve this?

Eg.



        
8条回答
  •  不知归路
    2020-12-29 18:34

    If you prefer to do things yourself without Lodash, and without getting verbose, try this uniq filter with optional uniq by property:

    const uniqFilterAccordingToProp = function (prop) {
        if (prop)
            return (ele, i, arr) => arr.map(ele => ele[prop]).indexOf(ele[prop]) === i
        else
            return (ele, i, arr) => arr.indexOf(ele) === i
    }
    

    Then, use it like this:

    const obj = [ { id: 1, name: 'bob' }, { id: 1, name: 'bill' }, { id: 1, name: 'bill' } ]
    obj.filter(uniqFilterAccordingToProp('abc'))
    

    Or for plain arrays, just omit the parameter, while remembering to invoke:

    [1,1,2].filter(uniqFilterAccordingToProp())

提交回复
热议问题