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?

1

2 Answers 2

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);

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

2 Comments

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
@Alan - I assumed modifiedBy as string. You need to change from b.modifiedBy.localeCompare(a.modifiedBy) to b.modifiedBy - a.modifiedBy
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>

1 Comment

That's how you do it in angular :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.