8

I am sorting my array like this:

array.sort((function(index) {
    return function(a, b){
        return (a[index] === b[index] ? 0 : (a[index] < b[index] ? -1 :1));
    };
})(0));

As you can see, it is sorted in ascending order.

My question is how do I toggle sorting? For example, if it is already in ascending order then how can I sort it in descending order and vice-versa?

I know to sort in descending I need to modify code like this:

array.sort((function(index) {
    return function(a, b) {
        return (a[index] === b[index] ? 0 : (a[index] < b[index] ? 1 :-1));
    };
})(0));

but I don't know how to toggle.

newfurniturey
  • 37,556
  • 9
  • 94
  • 102

5 Answers5

13

.reverse() will always reverse the order of an array, so on toggling, you just can call yourSortedArray.reverse()

var myArray = [1, 5, 8, 4, 0, 3, 6];
myArray.sort(); //[0, 1, 3, 4, 5, 6, 8]
myArray.reverse(); //[8, 6, 5, 4, 3, 1, 0]
Samir Karki
  • 151
  • 1
  • 6
  • 1
    not efficient - every toggling, it will traverse twice on the array : one for ascending sorting, and then reverse it – user2637293 May 15 '19 at 14:52
7

How about:

var array = [ 2,4,7,12,1,5 ];

array.toggled_sort = function () {
    var self=this;
    this.asc=!this.asc;
    return this.sort(function (l, r) {
        return l > r ? (self.asc ? 1 : -1) : l < r ? (self.asc ? -1 : 1) : 0;
    });
};

array.toggled_sort(); // ==> [ 1,2,4,5,7,12 ]
array.toggled_sort(); // ==> [ 12,7,5,4,2,1 ]
array.toggled_sort(); // ==> [ 1,2,4,5,7,12 ]
array.toggled_sort(); // ==> [ 12,7,5,4,2,1 ]
// etc.
pete
  • 705
  • 6
  • 8
  • Instead of array.toggled_sort you could assign the function to Array.prototype.toggled_sort to make toggled_sort available to all arrays. – pete Oct 16 '13 at 00:08
  • 1
    Can you help me with an array of this manner : [ "$55", "$110", "$101", "$89", "$75" ] ? – anusreemn Mar 18 '15 at 12:13
3

You were on the right track, you needed a third closure to store the state of toggle.

function fn(reversed){
    return function(){
        reversed = !reversed;
        return function(a,b){
            return (a==b ? 0 : a < b? -1 : 1) * (reversed ? -1 : 1);
        };
    };
};
// usage
var toggleSort = fn();
array.sort(toggleSort())

jsfiddle: http://jsfiddle.net/8JMuj/1/

Shanimal
  • 11,517
  • 7
  • 63
  • 76
2

If you know for certain that array is sorted then you can reverse the order by using a simple loop

var l = array.length;
for(i=0; i< l / 2; i++) {
   var t = array[i];
   array[i] = array[l - 1 - i];
   array[l - 1 - i] = t;
}

More simpler solution is to use reverse function (BTW, check this SO Q&A for different reversing algo and their performance)

If you don't know the initial state of you array then I will advise associating a custom property to an array that will track the sort order. For example,

function sortArray(a, isAscending) {
  var currentSort = a["my_sort_order"];
  if (typeof currentSort != 'boolean') {
     // assume it be unsorted, use sort alogorithm
     a.sort(function(a,b) { return isAscending ? a - b : b - a; }); // assuming numerical array, modify as per your needs
  } else if (currentSort != isAscending) {
     // sorted but in different order, reverse the order
     a.reverse(); // or use for loop
  }
  // set the sort order
  a["my_sort_order"] = isAscending ? true : false;
}
Community
  • 1
  • 1
VinayC
  • 47,395
  • 5
  • 59
  • 72
1
//Array sort by its object property can be implemented as this where sortType variable is used as the toggle parameter

//sortElement is the object property can be used as variable if you  need to select the property that which is used for sorting

//to sort by date property var elem1Var = new Date(elem1[sortElement]);

//to sort by string property var elem1Var =elem1[sortElement].toUpperCase();

var sortMethod = -1;
if(self.sortType == 'ASC'){
  sortMethod = 1;
}

dataArr.sort(function(elem1,elem2){
  var elem1Var = elem1[sortElement];
  var elem2Var = elem2[sortElement];

  if(elem1Var  < elem2Var){
       return -1*sortMethod;
  }

  if(elem1Var > elem2Var){
       return  1*sortMethod;
  }
  return 0;
 });