0

I have retrieved an array of test objects:

self.tests = response.data.tests;

The test objects that make up the array have a title and a modifiedBy field.

Is there some way that I can reorder the array by title ascending and then modifiedBy descending?

Alan2
  • 23,493
  • 79
  • 256
  • 450
  • Possible duplicate of [Sort array of objects by string property value in JavaScript](http://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value-in-javascript) – vidriduch Mar 17 '16 at 12:36

2 Answers2

3

You can try following

self.tests.sort(function(a, b) {
     var diff = a.title.localeCompare(b.title);
     return diff == 0? b.modifiedBy.localeCompare(a.modifiedBy) : diff;
});

Example

var arr = [

  {"title" : "title1", "modifiedBy" : "david1"},
  {"title" : "title1", "modifiedBy" : "david3"},
  {"title" : "title2", "modifiedBy" : "david2"},
  {"title" : "title1", "modifiedBy" : "david2"},
  {"title" : "title2", "modifiedBy" : "david1"}
]

arr.sort(function(a, b) {
  var diff = a.title.localeCompare(b.title);
  return diff == 0? b.modifiedBy.localeCompare(a.modifiedBy) : diff;
});


console.dir(arr);
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
  • I am getting a message saying localeCompare does not exist on type number. Note that I am using typescript and modifiedBy is a number. Thanks – Alan2 Mar 17 '16 at 12:59
  • @Alan - I assumed `modifiedBy` as string. You need to change from `b.modifiedBy.localeCompare(a.modifiedBy)` to `b.modifiedBy - a.modifiedBy` – Nikhil Aggarwal Mar 17 '16 at 13:01
2

If you want to sort data in js code, @nikhil's answer is great.

As I saw you have the angularjs tag in your question, if you want to sort data in template, it would be much easier. Here is the tip (replace + with -, if you want sort in reversed direction):

<div ng-repeat="obj in tests | orderBy: ['+title','+modifiedBy']>
   Title: {{obj.title}}
   Modified By: {{obj.modifiedBy}}
</div>
stanleyxu2005
  • 8,081
  • 14
  • 59
  • 94