3
var data = [{
    "priority": "1",
    "date": "01.03.2013",
    "title": "Yeah hi"
}, {
    "priority": "2",
    "date": "",
    "title": "Another title"
}, {
    "priority": "2",
    "date": "22.12.2013",
    "title": "Foo"
}, {
    "priority": "1",
    "date": "10.04.2013",
    "title": "Hey there"
}, {
    "priority": "2",
    "date": "15.08.2013",
    "title": "Hello world"
},
...
]

I've an multidimensional array and i want to sort it in a complex way.

  1. First sort by "priority" - highest priority first
  2. Then sort all items with the same priority by "date" - the next date near today first (there are only dates in future). And if an item don't have a date put it at the end.
  3. Sort all items with the same date (and all with no date) by "title" - alphabetically

The first step is no problem with data.sort() but then i've no plan for doing that. How to do that?

Philipp Kühn
  • 1,579
  • 2
  • 16
  • 25
  • Possible duplicate: http://stackoverflow.com/questions/3886165/javascript-sort-multidimensional-array – Control Freak May 08 '13 at 07:21
  • It would be a duplicate if i only want to sort by priority. But that isn't my problem... – Philipp Kühn May 08 '13 at 07:38
  • 1
    It is the same _principle_ though - you write your own little comparison function, that compares two elements according to all your criteria until it can decide which one is "smaller" than the other (or find out the are to be considered equal in the end). – CBroe May 08 '13 at 08:06

1 Answers1

5

One possible solution

data.sort(function(a,b) {
  if ( parseInt(a.priority) > parseInt(b.priority) )
     return 1;
  else if ( parseInt(a.priority) < parseInt(b.priority) )
     return -1;
  else if (a.date > b.date )
     return 1;
  else if ( a.date < b.date )
     return -1;
  else if (a.title > b.title )
     return 1;
  else if ( a.title < b.title )
     return -1;
  else
     return 0;
});

You should change your date field to be some kind of Epox or smth ( you can fix that by yourself ).

Demo : http://jsbin.com/adosuh/1/edit

drinchev
  • 19,201
  • 4
  • 67
  • 93