Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

removing duplicate objects inside of array

this question might look similar:

Question

but it isn’t.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have an array like this.

console.log output

serviceListData: Array(4) [ {…}, {…}, {…}, … ]
​​
0: Object { Id: 1939808, count: 1 }
​​
1: Object { Id: 1939808, count: 2 }
​​
2: Object { Id: 1940022, count: 1 }
​​
3: Object { Id: 1940022, count: 2 }

I want to remove objects with duplicate Id but also, I want to keep the latest value.
there’s no guarantee that the latest value will always be bigger like the example above.

it could be 2,1 2,1 in count property.

how can I do this?
keeping the latest count and removing duplicate Ids?

>Solution :

Assuming by "latest value" you mean highest index in the array, you can reduce the array and continue setting / resetting the value at the key, then take the values from the resulting object.

Something like:

Object.values(
  serviceListData
    .reduce((acc, next) => ({...acc, [next.Id]: next }), {})
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading