Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

87
Views
How to get second duplicate value rather than first value from JSON Array in React JS using lodash?

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.

7 months ago · Juan Pablo Isaza
1 answers
Answer question

0

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

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs