Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort JSON array based on its attributes value

This is the JSON Array what Iam getting:

    [
        {
            "Name" : "Sachin",
            "Age"  : "41",
            "Team" : "Mumbai"
        },
        {
            "Name" : "Dravid",
            "Age"  : "42",
            "Team" : "Rajasthan"
        },
        {
            "Name" : "Yuvraj",
            "Age"  : "31",
            "Team" : "Bangalore"
        }
    ]

But I need to sort this JSON array desc by the "Age" attribute. My desired JSON Array should be like below:

 [
    {
        "Name" : "Dravid",
        "Age"  : "42",
        "Team" : "Rajasthan"
    },
    {
        "Name" : "Sachin",
        "Age"  : "41",
        "Team" : "Mumbai"
    },
    {
        "Name" : "Yuvraj",
        "Age"  : "31",
        "Team" : "Bangalore"
    }
]

How to achieve this?

like image 667
thevan Avatar asked Apr 21 '26 06:04

thevan


1 Answers

var a = [
    {
        "Name" : "Sachin",
        "Age"  : "41",
        "Team" : "Mumbai"
    },
    {
        "Name" : "Dravid",
        "Age"  : "42",
        "Team" : "Rajasthan"
    },
    {
        "Name" : "Yuvraj",
        "Age"  : "31",
        "Team" : "Bangalore"
    }
];

   a.sort(function(x,y){return y["Age"]-x["Age"]});
   console.log(a);
like image 155
azero0 Avatar answered Apr 23 '26 19:04

azero0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!