Generic way of sorting JSON array by attribute

Something like a:

function predicateBy(prop){
   return function(a,b){
      if (a[prop] > b[prop]){
          return 1;
      } else if(a[prop] < b[prop]){
          return -1;
      }
      return 0;
   }
}

//Usage
yourArray.sort( predicateBy("age") );
yourArray.sort( predicateBy("name") );

You can sort arrays by any field with Alasql library:

var data = [{"name":"John", "age":"16"}, {"name":"Charles", "age":"26"}];

var res1 = alasql('SELECT * FROM ? ORDER BY name',[data]);
var res2 = alasql('SELECT * FROM ? ORDER BY age',[data]);
var res3 = alasql('SELECT * FROM ? ORDER BY age, name',[data]);
var res4 = alasql('SELECT * FROM ? ORDER BY age DESC, name ASC',[data]);

Try this example in jsFiddle.


See this example http://jsfiddle.net/W8Byu/1/

What I have done is stored the sort column Name in a variable and used in Sort function.

 var sortColumnName = "Name";

 function SortByName(x,y) {
      return ((x[sortColumnName]  == y[sortColumnName]) ? 0 : ((x[sortColumnName]>    y[sortColumnName]) ? 1 : -1 ));
    }