Reverse Sort on Second Click - Javascript
I have a function that sorts a json array after a link is clicked (so the function is called using an onclick) and the function works and can sort:
function sortArch(a,b) {
x = eval("a." + sort_type).toLowerCase();
y = eval("b." + sort_type).toLowerCase();
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
When I click the same button I want the function to reverse sort. The reversing is easy enough:
x = eval("a." + sort_type).toLowerCase();
y = eval("b." + sort_type).toLowerCase();
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
My problem is having the function know which way it needs to sort. I was thinking of using a boolean flag, but I can't seem to come up w开发者_如何转开发ith anything that works. I'm only looking for a way to keep track of which way it is sorted and then if the button is clicked it resorts with the second code snippet. Thanks in advanced!
You could do something like this:
function mySort(desc) {
var mod = desc ? -1 : 1;
return function(a,b) {
var lca = a[sort_type].toLowerCase(),
lcb = b[sort_type].toLowerCase();
return lca > lcb ? 1 * mod : lca < lcb -1 * mod : 0;
}
}
arr.sort(mySort(true)); //sort descending
arr.sort(mySort(false)); //sort ascending
btw: try not to use eval when you don't have to, it is slow and messy
You're almost done:
function compareFunc(sort_type, ascending) {
var direction = ascending ? 1 : -1;
return function(a, b) {
x = a[sort_type].toLowerCase();
y = b[sort_type].toLowerCase();
return direction * x.localeCompare(y);
}
}
Examples of use:
persons = [
{firstName: 'John', lastName: 'Foo'},
{firstName: 'Bob', lastName: 'Bar'}
];
// In your button click events, use compareFunc to generate the right function :
persons.sort(compareFunc('firstName', true));
// or
persons.sort(compareFunc('firstName', false));
// or
persons.sort(compareFunc('lastName', true));
// or
persons.sort(compareFunc('lastName', false));
Cheers!
Your idea of using a boolean flag is recommended:
function sort(reverse){
if(reverse){
//reverse sort code
}else{
//normal sort code
}
}
bottonElement.onclick = function(){sort(true);}; //or use addEventHandler
This also allows a sort()
cass, which automatically does a normal sort since undefined
is "falsy".
精彩评论