19

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.

2
  • So have you tried anything? The article you linked and what you actually want to do have nothing to do with JSON, by the way; you are manipulating regular Javascript data structures, while JSON is a string serialization of such structures. Commented Jun 19, 2012 at 11:05
  • 1
    you're right. I did not formulate the question correctly. Commented Jun 19, 2012 at 11:20

3 Answers 3

81

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") );
Sign up to request clarification or add additional context in comments.

3 Comments

@Engineer: Is this currying ? Nice one though + 1
how is this exactly working? what's being assigned to a and what's being assigned to b and how?
@WeDoTDD See the Array.sort docs
5

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.

1 Comment

This should be the accepted answer, This helps provides all sql functionalities besides only sorting.. works wonders much thanks !! :)
4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.