代码之家  ›  专栏  ›  技术社区  ›  Harry

如何过滤javascript中值最低的重复项

  •  -2
  • Harry  · 技术社区  · 5 年前

    我有一个如下所示的对象数组,我需要删除所有具有最低价格值的重复项,例如价格为“8”的项“book”应被删除,因为它是最低的帐面价格,我如何才能继续执行此操作?

    let array = [
          {
            item: "Pen",
            price: 3
          },
          {
            item: "Book",
            price: 10
          },
          {
            item: "Pen",
            price: 6
          },
          {
            item: "Book",
            price: 8
          }
        ];
    
    2 回复  |  直到 5 年前
        1
  •  1
  •   Ori Drori    5 年前

    将项目减少为对象。对于每个项,如果它在对象中不存在,或者它的价格高于对象中相同类型的当前项,则使用 item 属性作为键。使用转换回数组 Object.values() :

    const array = [{"item":"Pen","price":3},{"item":"Book","price":10},{"item":"Pen","price":6},{"item":"Book","price":8}]
    
    const result = Object.values(array.reduce((r, o) => {
      if(!r[o.item] || o.price > r[o.item].price) r[o.item] = o
    
      return r
    }, {}))
    
    console.log(result)
        2
  •  2
  •   Medet Tleukabiluly    5 年前

    let array = [{
        item: "Pen",
        price: 3
      },
      {
        item: "Book",
        price: 10
      },
      {
        item: "Pen",
        price: 6
      },
      {
        item: "Book",
        price: 8
      }
    ];
    
    // remove dups
    let grouped = array.reduce(function(all, next) {
      if (all[next.item]) {
        all[next.item].push(next.price)
      } else {
        all[next.item] = [next.price]
      }
      return all
    }, {})
    
    // remove smallest values
    let result = Object.keys(grouped).map(function(key) {
      return {
        item: key,
        price: Math.max.apply(null, grouped[key])
      }
    })
    
    console.log(result)