-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.

3
  • do you have access to moment.js? Commented Oct 17, 2014 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. Commented Oct 17, 2014 at 14:35
  • 3
    Discussed at Meta right now. Commented Oct 17, 2014 at 14:36

1 Answer 1

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...

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.