-1

I have an array with objects that contain titles and dates.

[{
   title: 'Some title'
   date: '12.00 PM 17/10/2014'
},
...
]

I need to sort that values by date and alphabetically in the same time, the result should look like follows:

1.00 PM - Btitle
1.00 PM - Bztitle
1.00 PM - Ctitle
3.00 PM - Atitle
3.00 PM - Btitle

Should I create additional arrays to remember state etc? Or maybe it's possible to do within single sort method.

Kosmetika
  • 20,774
  • 37
  • 108
  • 172
  • do you have access to moment.js? – gh9 Oct 17 '14 at 14:33
  • Tip: If you could get a `string` out of the `date/time` in the format `YYYY/MM/DD HH:mm:ss` and concatenate it with the `title`, you then could sort the `array` by this _merged_ data. – emerson.marini Oct 17 '14 at 14:35
  • 3
    Discussed at [Meta](http://meta.stackoverflow.com/questions/274630/should-we-add-a-do-my-work-for-me-close-reason?cb=1) right now. – Teemu Oct 17 '14 at 14:36

1 Answers1

12

You can do it in a single sort method. The bones of it are:

yourArray.sort(function(a, b) {
    var adate = /* ...parse the date in a.date... */,
        bdate = /* ...parse the date in b.date... */,
        rv = adate - bdate;
    if (rv === 0) {
        rv = a.title.localeCompare(b.title);
    }
    return rv;
});

I'll leave the parsing of that odd date format as an exercise for the reader...

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875