Reputation: 23
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
Upvotes: 2
Views: 80
Reputation: 8239
Simply maintain a map corresponding to each id, and update the map if the existing value is less than new value, Object.values()
on the map will give you the desired result:
let testArray = [ { id: 1, value: "test1", value1: 1 }, { id: 2, value: "test2", value1: 1 }, { id: 1, value: "test3", value1: 5 } ];
let filtered = Object.values(testArray.reduce((acc, curr)=>{
acc[curr.id] = acc[curr.id] && acc[curr.id].value1 > curr.value1 ? acc[curr.id] : curr;
return acc;
},{}));
console.log(filtered);
Upvotes: 0
Reputation: 386560
You could search for the index and if valid check the value and update the array if the value is greater.
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) => {
let index = accumulator.findIndex(({ id }) => id === current.id)
if (index === -1) {
accumulator.push(current);
} else if (accumulator[index].value1 < current.value1) {
accumulator[index] = current;
}
return accumulator;
}, []);
console.log(filtered);
Upvotes: 2