1

this question might look similar:

Question

but it isn't.

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?

yasxcv
  • 65
  • 7
  • 3
    Iterate through the array and assign a key/value to an object with the id as the key. Then you can take the `Object.values` of them to get an array back. – possum Nov 27 '22 at 19:30

1 Answers1

3

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 }), {})
)
Tom
  • 7,640
  • 1
  • 23
  • 47