【问题标题】:Sorting an array depending on prices inside of an object [duplicate]根据对象内部的价格对数组进行排序[重复]
【发布时间】:2021-09-09 02:50:15
【问题描述】:

我正在为以下使用 Angular 的想法而苦苦挣扎:

有一个加油站列表,其中包含一个包含多个价格值的数组(最新的是最重要的)。现在的目标是根据我们在数组中得到的最新价格对列表中的所有电台进行排序。

这是一个示例站:

{
"id": 2,
"name": "Agrola Top Shop",
"street": "Untere Rütenenstrasse 1",
"postCode": 4310,
"place": "Rheinfelden",
"canton": "AG",
"country": "CHE",
"coordinates": [
    47.563595,
    7.827416
],
"provider": "Agrola",
"owner": "Industrielle Werke Basel",
"paymentMethods": [
    "bar",
    "Tankkarte (Agrola)",
    "Maestro",
    "Mastercard",
    "Visa"
],
"openingHours": [
     "06:00 – 22:00",
     "06:00 – 22:00",
     "06:00 – 22:00",
     "06:00 – 22:00",
     "06:00 – 22:00",
     "06:00 – 22:00",
     "07:00 – 21:00"
],
"Open24H": 1,
"mail": "t@iwb.ch",
"url": "www.iwb.ch",
"phone": [
"+41 61 000 00 00"
],
"GasPricesNGV": [
{
  "Price": 1.48,
  "LastGasPriceUpdate": "2009-07-01"
},
{
  "Price": 1.55,
  "LastGasPriceUpdate": "2010-07-21"
}
]
}

使用数组中位置 [0] 的最新 Gas-Price,我想确定一个站点是否属于 10% 最便宜的站点。但是我怎样才能实现我能够使用对象内部的值和数组进行排序呢?

【问题讨论】:

    标签: javascript arrays json sorting


    【解决方案1】:

    您可以使用数组方法sort() 对它们进行排序,取第一个price 值并首先与下一个项目比较price 值。

    const data = [{
      "id": 2,
      "GasPricesNGV": [{
          "Price": 1.55,
          "LastGasPriceUpdate": "2009-07-01"
        },
        {
          "Price": 1.55,
          "LastGasPriceUpdate": "2010-07-21"
        }
      ]
    }, {
      "id": 3,
      "GasPricesNGV": [{
          "Price": 1.99,
          "LastGasPriceUpdate": "2009-07-01"
        },
        {
          "Price": 1.99,
          "LastGasPriceUpdate": "2010-07-21"
        }
      ]
    }, {
      "id": 4,
      "GasPricesNGV": [{
          "Price": 0.55,
          "LastGasPriceUpdate": "2009-07-01"
        },
        {
          "Price": 0.55,
          "LastGasPriceUpdate": "2010-07-21"
        }
      ]
    }];
    
    const sorted = data.sort((a, b) => {
      return a.GasPricesNGV[0].Price - b.GasPricesNGV[0].Price;
    });
    
    
    console.log(sorted);

    【讨论】:

      猜你喜欢
      • 2020-05-03
      • 2021-07-20
      • 2014-05-29
      • 1970-01-01
      • 2017-06-02
      • 2020-04-21
      • 1970-01-01
      • 2018-05-19
      • 2018-12-08
      相关资源
      最近更新 更多