Reputation: 3004
I have an array that looks like:
var array = [
{ name: "product1", rating: 1 },
{ name: "product3", rating: 2 },
{ name: "product1", rating: 2 },
{ name: "product2", rating: 2 },
{ name: "product3", rating: 1 },
{ name: "product4", rating: 2 },
{ name: "product2", rating: 2 }
]
I am wanting to eliminate objects with duplicate names, BUT want to keep the one with the lowest rating. Thus ending up with:
var newarray = [
{ name: "product1", rating: 1 },
{ name: "product2", rating: 2 },
{ name: "product3", rating: 1 },
{ name: "product4", rating: 2 }
]
Using filter I end up with two product1 & product3 in the newarray due to different ratings. Targeting by name, I end up with the object in the array based on its original position, which would not work.
I am looking for a way with vanilla javascript to compare the value for each of the duplicated objects and push the one with the lowest value.
Each product name could appear up to three times. Values would only be 1 or 2.
Upvotes: 0
Views: 70
Reputation: 503
Since reduce is already mentioned, I thought I would give an example of using .filter() as you get some flexibility in a different area.
var array = [
{ name: "product1", rating: 1 },
{ name: "product3", rating: 2 },
{ name: "product1", rating: 2 },
{ name: "product2", rating: 2 },
{ name: "product3", rating: 1 },
{ name: "product4", rating: 2 },
{ name: "product2", rating: 2 }
];
var newArray = array.filter((value,iteration,arr)=>{
for(var i = 0; i < arr.length; i++){
if(value.name === arr[i].name && iteration != i){
if(value.rating > arr[i].rating){
return false
}else if(value.rating === arr[i].rating && iteration > i){
return false
}
}
}
return true
});
/*newArray
[
{ name: 'product1', rating: 1 },
{ name: 'product2', rating: 2 },
{ name: 'product3', rating: 1 },
{ name: 'product4', rating: 2 }
]*/
Reduce should be faster in most cases, but you never know.
Upvotes: 0
Reputation: 14891
You could use reduce
to group by name with the element has lowest rating of each name
const array = [
{ name: "product1", rating: 1 },
{ name: "product3", rating: 2 },
{ name: "product1", rating: 2 },
{ name: "product2", rating: 2 },
{ name: "product3", rating: 1 },
{ name: "product4", rating: 2 },
{ name: "product2", rating: 2 },
]
const res = Object.values(
array.reduce((acc, el) => {
if (!acc[el.name] || acc[el.name].rating > el.rating) {
acc[el.name] = el
}
return acc
}, {})
)
console.log(res)
Upvotes: 3