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
  • 211,518
  • 52
  • 313
  • 390

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,686
  • 15
  • 57
  • 82
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
  • 4,077
  • 38
  • 41