0

I need to sort an array of objects by the two fields. I need it to be as least computationally heavy as possible.

This is how the array of objects looks

let arr = [
    {
        name: 'Liate',
        surname: 'Tsek'
    },
    ...
]

This is how I am doing it

let unique = [...new Set(arr.map(item => item.name))]

This only works for the 1st field, how can I get it to work with both?

1 Answer 1

0
let seen = new Set()
let uniArr = arr.filter(entry => {
    /*
    ** Create unique key of code and segment
    */
    const key = entry.name+ "-" + entry.surname
    /*
    **  Check if the key does not exist in the SET
    */
    const keep = !seen.has(key)
    /*
    ** If keep doesn't exist, add it to the set
    */
    if (keep)
        seen.add(key)
    /*
    ** Return
    */
    return keep
})

This works given that the delimiter you use to join the fields will never appear in either fields. Hope it helps

2
  • Hi Thank you, this worked for me. I am keen to know what the Set is? I am new to NodeJS apologies.
    – Tsek-Coder
    Commented May 10, 2018 at 8:54
  • I filter with ES6 Set, I recommend learning more about it before continuing
    – adot
    Commented May 10, 2018 at 8:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.