I have an array of objects. I want to keep the object which has the highest value but remove any duplicates.
For example, in the following array of objects, I want to remove the object that has a duplicate price and keep the one with the highest value. -
const data = [{
"title": "The Little Prince",
"price": 49,
"value": 20
},
{
"title": "Watchmen",
"price": 49,
"value": "40"
}
]
/**
const desiredOutput = [
{
"title":"Watchmen",
"price": 49,
"value": 40
}
]
**/
Here's my code but it doesn't remove the object with the same price and outputs the same array -
const data = [{
"title": "The Little Prince",
"price": 49,
"value": 20
},
{
"title": "Watchmen",
"price": 49,
"value": "40"
}
]
const removeDuplicatePrice = plans => {
const prices = [];
const updatedBooks = plans.filter(el => {
const matchingRack = prices.find(
element =>
element.price === el.price
);
let {
price,
value
} = el;
if (!matchingRack) {
prices.push({
price,
value
});
return true;
}
if (el.value > matchingRack.value) {
matchingRack.value = el.value;
return true;
}
return false;
});
return updatedBooks;
};
console.log(removeDuplicatePrice(data));