Search code examples
javascriptarraysnode.jssortingjavascript-objects

Sorting an array of objects on both ascending and descending order on same click


I have an array of objects:

var arr = [{
  title: "finance",
  book: "book1"
},
{
  title: "nature",
  book: "book2"
},
{
  title: "programming",
  book: "book3"
}]

HTML:

<th><a href="#" ng-click="controller.sortTitle()">TITLE</a></th>

Right now I have implemented a basic sorting logic below

JAVASCRIPT(AngularJS controller):

self.sortTitle = function () {
    self.arr= self.arr.sort((a, b) => (a.title > b.title) ? 1 : -1);
}

This JavaScript function is currently sorting it in ascending order only based on title. How do I write a logic that sorts it on either order, i.e. click1 should sort it in ascending and click2 should reverse and set it in descending? Basically reversing the sort everytime it is clicked.


Solution

  • You can create a property on self like isAscending and default to true or false (whatever you want initially) based on which sort order will be executed and flip isAscending every time the sort fn runs.

    self.isAscending = true;
    
    self.sortTitle = function () {
     if(self.isAscending){ 
       self.arr= self.arr.sort((a, b) => (a.title > b.title) ? 1 : -1);
     }else{
       self.arr= self.arr.sort((a, b) => (a.title > b.title) ? -1 : 1);
     }
     self.isAscending = !self.isAscending;
    }