Link to home
Start Free TrialLog in
Avatar of Neil Thompson
Neil ThompsonFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Sort part of an array by value of specific key

Hi

I'm unsure how to sort by one of the key values in this array (it's part of a bigger one) but I want to loop through ERates->In and display "RateBreak" and "Rate" BUT sort by "Hours"

I'll obviously then do the same for ERates->Out

Thanks

  "ERates": {
    "In": [
      {
        "RateBreak": "½ Hour",
        "Rate": 100,
        "Hours": 0.5,
        
      },
      {
        "RateBreak": "1 Hour",
        "Rate": 200,
        "Hours": 1,
        
      },
      {
        "RateBreak": "Overnight",
        "Rate": 1000,
        "Hours": 10
      },
      {
        "RateBreak": "15 mins",
        "Rate": 70,
        "Hours": 0.25
        
      }
    ],
    "Out": [
      {
        "RateBreak": "½ Hour",
        "Rate": 150,
        "Hours": 0.5
        
      },
      {
        "RateBreak": "1 Hour",
        "Rate": 250,
        "Hours": 1
        
      },
      {
        "RateBreak": "Overnight",
        "Rate": 1200,
        "Hours": 10
      },
      {
        "RateBreak": "15 mins",
        "Rate": 100,
        "Hours": 0.25
        
      }
    ]
  }

Open in new window

Avatar of ste5an
ste5an
Flag of Germany image

Use the .sort() function:

<!DOCTYPE html>
<html>
<body>
    <script>
        var obj={
            "ERates": {
                "In":  [{ "RateBreak": "½ Hour", "Rate": 100, "Hours": 0.5, },
                        { "RateBreak": "1 Hour", "Rate": 200, "Hours": 1, },
                        { "RateBreak": "Overnight", "Rate": 1000, "Hours": 10 },
                        { "RateBreak": "15 mins", "Rate": 70, "Hours": 0.25 }],
                "Out": [{ "RateBreak": "½ Hour", "Rate": 150, "Hours": 0.5 },
                        { "RateBreak": "1 Hour", "Rate": 250, "Hours": 1 },
                        { "RateBreak": "Overnight", "Rate": 1200, "Hours": 10 },
                        { "RateBreak": "15 mins", "Rate": 100, "Hours": 0.25 }]
            }
        };

        var sorted = obj.ERates.In.sort(function (a, b) { return a.Hours - b.Hours; });
        console.log(JSON.stringify(sorted, null, 1));
    </script>
</body>
</html>

Open in new window


Line 18 in modern JS

var sorted = obj.ERates.In.sort( (a, b) => a.Hours - b.Hours );

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@Ste5an - I thought this was a PHP question?
oops..
Avatar of Neil Thompson

ASKER

Many thanks once again Julian you come to my assistance.
You are welcome Neil.