Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort multidimensional array by multiple criteria

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?

like image 293
Philipp Kühn Avatar asked Dec 04 '25 18:12

Philipp Kühn


1 Answers

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

like image 153
drinchev Avatar answered Dec 06 '25 09:12

drinchev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!