猿问

Javascript:有条件地从数组中删除重复的对象

我有一个看起来像这样的数组:


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 = [

  { name: "product1", rating: 1 },

  { name: "product2", rating: 2 },

  { name: "product3", rating: 1 },

  { name: "product4", rating: 2 }

]

使用过滤器,由于评级不同,我最终在 newarray 中得到两个 Product1 和 Product3。通过名称定位,我最终得到了基于其原始位置的数组中的对象,这是行不通的。


我正在寻找一种使用普通 JavaScript 的方法来比较每个重复对象的值并推送具有最低值的对象。


每个产品名称最多可以出现三次。值只能是 1 或 2。


慕的地10843
浏览 93回答 2
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)

慕哥9229398

由于已经提到了reduce,我想我会给出一个使用.filter()的例子,因为你可以在不同的领域获得一些灵活性。var array = [&nbsp; { name: "product1", rating: 1 },&nbsp; { name: "product3", rating: 2 },&nbsp; { name: "product1", rating: 2 },&nbsp; { name: "product2", rating: 2 },&nbsp; { name: "product3", rating: 1 },&nbsp; { name: "product4", rating: 2 },&nbsp; { name: "product2", rating: 2 }];var newArray = array.filter((value,iteration,arr)=>{&nbsp; &nbsp; for(var i = 0; i < arr.length; i++){&nbsp; &nbsp; &nbsp; &nbsp; if(value.name === arr[i].name && iteration != i){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(value.rating > arr[i].rating){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }else if(value.rating === arr[i].rating && iteration > i){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return true});/*newArray[&nbsp; &nbsp; { name: 'product1', rating: 1 },&nbsp; &nbsp; { name: 'product2', rating: 2 },&nbsp; &nbsp; { name: 'product3', rating: 1 },&nbsp; &nbsp; { name: 'product4', rating: 2 }]*/在大多数情况下,Reduce 应该更快,但你永远不知道。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答