1

My Javascript array has the fields title, modifiedDate and seq

I already have this sort function:

            self.tests.sort(function (a, b) {
                var diff = a.title.localeCompare(b.title);
                var aDate = a.modifiedDate || "";
                var bDate = b.modifiedDate || "";
                return diff == 0 ? bDate.localeCompare(aDate) : diff;
            });

Now I need to extend it to sort by

  1. title
  2. modifiedDate
  3. seq

I've only every seen a two field sort like this. How can I extend it to sort on the seq field also?

Alan2
  • 23,493
  • 79
  • 256
  • 450
  • SideNote: if you don't get an acceptable answer, take a look at [lodash](https://lodash.com/docs#sortBy)'s _sortBy method, or this [thenBy](https://github.com/Teun/thenBy.js) repo. – mugabits Apr 06 '16 at 14:54
  • Is your array an array of objects? – mugabits Apr 06 '16 at 15:02

1 Answers1

4

You could chain them together with logical OR ||, because on every equal, it takes the next comparison.

Assuming, that seq is a number.

self.tests.sort(function (a, b) {
    var aDate = a.modifiedDate || "",
        bDate = b.modifiedDate || "";
    return a.title.localeCompare(b.title) || bDate.localeCompare(aDate) || a.seq - b.seq;
});
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392