'How to get second duplicate value rather than first value from JSON Array in React JS using lodash? [duplicate]

I am working on one project where I need to remove duplicate values from JSON array object with some specification in react JS. I have tried to remove using _.uniqBy but in the output it took very first value from duplicate value which is I don't want.

Suppose You have an array JSON like:

[ { id: 1, name: 'bob' }, { id: 2, name: 'bill' }, { id: 1, name: 'alice' } ]

using _.uniqBy I got [ { id: 1, name: 'bob' }, { id: 2, name: 'bill' }] this output.

but I want [ { id: 2, name: 'bill' }, { id: 1, name: 'alice' } ] this output.

As you can see I want output whose name is alice not bob along with id:1.

Can anyone help me? Thank you.



Solution 1:[1]

My first thought is to use a reduce, and shove the items in a map, then get the values:

   Object.values(items.reduce((map, item) => ({ ...map, [item.id]: item }), {}))

This is probably not very efficient though if you're dealing with large arrays of have performance concerns.

It's a quick and dirty one-liner. If you want something more efficient I'd take a look at the lodash source code and tweak it to your needs or write something similar:

https://github.com/lodash/lodash/blob/2f79053d7bc7c9c9561a30dda202b3dcd2b72b90/.internal/baseUniq.js

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Joe