I have an array of Objects with duplicates. I want to remove those duplicates but need to get the "duplicate" where a third key has the higher value.
Tried this solutions: Remove duplicates from an array of objects in JavaScript but this gives me always the first duplicate and I need to check which has the higher value of third keys.
let testArray = [
{ id: 1, value: "test1", value1: 1 },
{ id: 2, value: "test2", value1: 1 },
{ id: 1, value: "test3", value1: 5 }
];
let filtered = testArray.reduce((accumulator, current) => {
if (!accumulator.find(({ id }) => id === current.id)) {
accumulator.push(current);
}
return accumulator;
}, []);
console.log(filtered);
/*
Result is:
[ { id: 1, value: 'test1', value1: 1 },
{ id: 2, value: 'test2', value1: 1 } ]
Result desired:
[ { id: 1, value: 'test1', value1: 5 },
{ id: 2, value: 'test2', value1: 1 } ]
*/
I expect a result like:
[ { id: 1, value: 'test1', value1: 1 },
{ id: 2, value: 'test2', value1: 5 } ]
of the testArray