0

trying to work this out but not sure about it really

I have a JSON object which contains multiple items like below

DATA_TABLE = [{"rownum": 0, "Surname": "Doe", "Firstname": "John", "Dob": "1 Jan 1980"}...]

I want to sort the data by DOB then Surname then firstname, to get the same result like for example the sql statement

ORDER BY Dob, Surname, Firstname
georg
  • 204,715
  • 48
  • 286
  • 369

2 Answers2

1

You may use the following code:

DATA_TABLE.sort(function(a, b) {
  return new Date(a.Dob) - new Date(b.Dob) 
  || ((a.Surname   < b.Surname  ) ? -1 : (a.Surname   > b.Surname  ) ? 1 : 0)
  || ((a.Firstname < b.Firstname) ? -1 : (a.Firstname > b.Firstname) ? 1 : 0) ;
});

JsFiddle Sample

Ashraf Bashir
  • 9,356
  • 13
  • 53
  • 80
0

You can do it with Alasql library:

 var DATA_TABLE = [{"rownum": 0, "Surname": "Doe", "Firstname": "John", "Dob": "1 Jan 1980"},
          {"rownum": 1, "Surname": "America", "Firstname": "Captain", "Dob": "1 Jan 1940"},];

 var res = alasql('SELECT *, DATE(Dob) AS d FROM ? ORDER BY d, Surname, Firstname',[DATA_TABLE]);

Try this example in jsFiddle.

Due the original Dob column has a string type, I include additional column "d" for proper sorting.

agershun
  • 3,973
  • 37
  • 40