Sort JSON array based on its attributes value
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);
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);
var _ = require('underscore');var data = ...your data...console.log(_.sortBy(data, 'Age').reverse());