Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
123
rated 0 times [  124] [ 1]  / answers: 1 / hits: 44019  / 12 Years ago, thu, january 24, 2013, 12:00:00

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.


More From » javascript

 Answers
18

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

[#80654] Wednesday, January 23, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mickaylag

Total Points: 333
Total Questions: 108
Total Answers: 93

Location: Solomon Islands
Member since Fri, Oct 8, 2021
3 Years ago
;