0

I am struggling with the following idea working with Angular:

There is a list of Gas-Stations containing an array with multiple price-values (the latest one is the most important). The aim is now to sort all stations inside the list depending on the latest price we got inside the array.

Here is an example station:

{
"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"
}
]
}

Using the latest Gas-Price inside the array at position [0] i would like to determine wheter a station is part of the 10% cheapest stations or not. But how can i achieve that i am able to sort using a value inside the object and a array?

Snirka
  • 602
  • 1
  • 5
  • 19
Dominik
  • 49
  • 5

1 Answers1

0

You could sort them using array method sort(), take the first price value and compare to the next items first price value.

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);
axtck
  • 3,707
  • 2
  • 10
  • 26