TAGS :Viewed: 15 - Published at: a few seconds ago

[ Generic way of sorting JSON array by attribute ]

I found out how to sort a JSON array at http://www.devcurry.com/2010/05/sorting-json-array.html

Now I want to sort it in a generic way; so that my sorting function knows which attribute to sort by.

For example if my array is

[
  {
    "name": "John",
    "age": "16"
  },
  {
    "name": "Charles",
    "age": "26"
  }
]

I want to avoid writing different if cases to know if I should sort by name or age. I just want to pass a parameter 'name' or 'age' and my sorting function should know what to do.

Thanks.

Answer 1


Something like a:

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
yourArray.sort( predicatBy("age") );
yourArray.sort( predicatBy("name") );

Answer 2


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 ));
    }

Answer 3


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.