Reputation: 10354
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?
Upvotes: 2
Views: 2115
Reputation: 5193
Try this:
var arr = [
{
"Name" : "Sachin",
"Age" : "41",
"Team" : "Mumbai"
},
{
"Name" : "Dravid",
"Age" : "42",
"Team" : "Rajasthan"
},
{
"Name" : "Yuvraj",
"Age" : "31",
"Team" : "Bangalore"
}
]
var prop = "Age"
arr.sort(function(a,b){
var cmp = -1
if (a.hasOwnProperty(prop) && b.hasOwnProperty(prop)){
var a_prop_value = parseFloat(a[prop])
var b_prop_value = parseFloat(b[prop])
if (isNaN(a_prop_value) || isNaN(b_prop_value)){
//string comp
cmp = a[prop].localeCompare(b[prop])
}else{
cmp = a_prop_value - b_prop_value > 0? 1 : a_prop_value - b_prop_value ==0? 0:-1
}
}
return cmp;
});
Upvotes: 1
Reputation: 674
The naive answer would be to use Array.prototype.sort([compareFunction]). Something in the way of:
function compareAgeProperty(a,b) {
return (parseInt(a.Age) < parseInt(b.Age)) ? -1 : 1;
}
var arr = [/* your array's data here */];
arr.sort(compareAgeProperty);
I'd recommend you take a look at: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
Your Age property is a string, and thus compared as a string, meaning '80'<'9'===true. Parsing the property should solve this issue.
Upvotes: 1
Reputation: 2310
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);
Upvotes: 6
Reputation: 3272
Use the following generic function predicateBy to sort your data by the desired field
var data=[
{
"Name" : "Sachin",
"Age" : "41",
"Team" : "Mumbai"
},
{
"Name" : "Dravid",
"Age" : "42",
"Team" : "Rajasthan"
},
{
"Name" : "Yuvraj",
"Age" : "31",
"Team" : "Bangalore"
}
]
function predicatBy(prop){
return function(a,b){
if( a[prop] > b[prop]){
return 1;
}else if( a[prop] < b[prop] ){
return -1;
}
return 0;
}
}
//Usage
data.sort( predicatBy("age") );
console.log(data);
Upvotes: 2
Reputation: 10145
var _ = require('underscore');
var data = ...your data...
console.log(_.sortBy(data, 'Age').reverse());
Upvotes: 1