this question might look similar:
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?
Advertisement
Answer
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 }), {}) )