【问题标题】:How to get min value of an attribute from array of arrays如何从数组数组中获取属性的最小值
【发布时间】:2020-09-17 07:30:12
【问题描述】:

从下面的数组中,我需要从属性中获取具有最低“成本”值的元素。 “属性”是每个元素中的另一个数组。

所以它应该给我 productId - 1 的条目,因为它的成本最低 - 100。 我们如何在 React/javascript 中做到这一点?请帮忙。

[
{
    "productId": 1,
    "attributes": [
        {
            "id": 101,
            "name": "quantity",
            "value": 10
        },
        {
            "id": 102,
            "name": "description",
            "value": "product 1"
        },
        {
            "id": 103,
            "name": "cost",
            "value": 100
        }
    ]
},
{
    "productId": 2,
    "attributes": [
        {
            "id": 101,
            "name": "quantity",
            "value": 5
        },
        {
            "id": 102,
            "name": "description",
            "value": "product 2"
        },
        {
            "id": 103,
            "name": "cost",
            "value": 150
        }
    ]
},
{
    "productId": 3,
    "attributes": [
        {
            "id": 101,
            "name": "quantity",
            "value": 20
        },
        {
            "id": 102,
            "name": "description",
            "value": "product 3"
        },
        {
            "id": 103,
            "name": "cost",
            "value": 200
        }
    ]
}

]

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    我的想法是通过 asc 使用排序数组并获得第一个:

    let min = arr.sort((a, b) => a.attributes.find(e => e.name === "cost")["value"] - b.attributes.find(e => e.name === "cost")["value"])[0];
    

    【讨论】:

      【解决方案2】:

      这个方法应该可以做到:

      
      yourArray.reduce(
        (acc, cur) => {
          let cost = cur.attributes.filter((a) => a.name == "cost")[0].value;
          if (cost < acc.cheapestCost) acc.cheapestProduct = cur;
          return acc;
        },
        { cheapestProduct: {}, cheapestCost: 1000000 }
      ).cheapestProduct;
      
      
      

      【讨论】:

        【解决方案3】:
        const lowest = givenArray.reduce((prev, next) => {
          return (prev.attributes[2].value < next.attributes[2].value) ? prev : next
        })
        

        【讨论】:

          猜你喜欢
          • 2023-01-05
          • 2019-03-15
          • 1970-01-01
          • 2013-10-13
          • 2023-03-18
          • 2019-12-25
          • 2020-03-24
          • 1970-01-01
          • 2017-05-02
          相关资源
          最近更新 更多