【问题标题】:get a single object from an array, according to condition by one of its keys根据其中一个键的条件从数组中获取单个对象
【发布时间】:2018-07-27 20:22:54
【问题描述】:

我有一个对象数组,我想只获取数量最多的对象,在这个例子中是 'id': 4 的对象,并尝试使用 javascript 的 filter 属性,但我没有做到了,否则我能做到吗?

[
  {
    "id": 1,
    "quantity": 10,
    "price": 80
  },
  {
    "id": 2,
    "quantity": 30,
    "price": 170
  },
  {
    "id": 3,
    "quantity": 50,
    "price": 230
  },
  {
    "id": 4,
    "quantity": 100,
    "price": 100
  }
]

【问题讨论】:

  • @certainPerformance 你怎么find 数量最多?

标签: javascript arrays ecmascript-6 javascript-objects


【解决方案1】:

在这种情况下,reduce 是正确的选择:

const most = array.reduce((a, b) => a.quantity > b.quantity ? a : b);

【讨论】:

    【解决方案2】:

    您可以通过quantity 对数组进行排序,然后从排序后的数组中取出第一项。

    var a = [{
        "id": 1,
        "quantity": 10,
        "price": 80
    }, {
        "id": 2,
        "quantity": 30,
        "price": 170
    }, {
        "id": 3,
        "quantity": 50,
        "price": 230
    }, {
        "id": 4,
        "quantity": 100,
        "price": 100
    }]
    
    a.sort((obj1, obj2)=> obj2.quantity - obj1.quantity)[0]
    // {id: 4, quantity: 100, price: 100}
    

    【讨论】:

      【解决方案3】:

      只是提供另一个答案——使用 math 库有点矫枉过正

      let a = [
        {
          "id": 1,
          "quantity": 10,
          "price": 80
        },
        {
          "id": 2,
          "quantity": 30,
          "price": 170
        },
        {
          "id": 3,
          "quantity": 50,
          "price": 230
        },
        {
          "id": 4,
          "quantity": 100,
          "price": 100
        }
      ]
      
      let result = a.find(function(item){ return item.quantity ===  Math.max.apply(Math,a.map(function(item){return item.quantity;})); })
      
      console.log(result)
      

      这使用数学库来查找最大数量,然后在数组中找到具有该数量的对象。不是最好的答案,而是解决问题的不同方式:)

      【讨论】:

        【解决方案4】:

        这将映射 JSON 对象数组并跟踪数量最多的对象的索引。

        let indexOfHighest = 1
        arrayOfObject.map((obj,index) = {
           if(obj.quantity > arrayOfObject[indexOfHighest].quantity)
           {
             indexOfHighest = index
           }
        
        })
        

        【讨论】:

        • 虽然此代码 sn-p 可能是解决方案,但 including an explanation 确实有助于提高您的帖子质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
        猜你喜欢
        • 2018-06-18
        • 2021-11-07
        • 1970-01-01
        • 2020-09-17
        • 2019-04-05
        • 1970-01-01
        • 2017-08-03
        • 2020-02-07
        • 1970-01-01
        相关资源
        最近更新 更多