2 回答
TA贡献1784条经验 获得超2个赞
您可以使用reduce按名称分组,其中每个名称的评级最低的元素
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)
TA贡献1877条经验 获得超6个赞
由于已经提到了reduce,我想我会给出一个使用.filter()的例子,因为你可以在不同的领域获得一些灵活性。
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 应该更快,但你永远不知道。
添加回答
举报