Mittwoch, 26. Mai 2010

Javascript sorting functions

I recently used some array sorting in javascript (array.sort([callback])). Here are some (hopefully) useful functions which can sort strings and numbers (including currency values) ascending and descending.

// sorting functions
// sort numbers asc
function sortNumberAsc(a, b) {
    var sortBy = $.fn.microView.sortedBy;
    aa = a[sortBy].replace(/[^0-9.,]/, '');
    bb = b[sortBy].replace(/[^0-9.,]/, '');
    return (aa - bb)
}; 
// sort numbers desc
function sortNumberDesc(a, b) {
    var sortBy = $.fn.microView.sortedBy;
    aa = a[sortBy].replace(/[^0-9.,]/, '');
    bb = b[sortBy].replace(/[^0-9.,]/, '');
    return (bb - aa)
}; 
// sort text asc
function sortTextAsc(a,b){
    var sortBy = $.fn.microView.sortedBy;
    if(a[sortBy] == b[sortBy]){
 if(a[sortBy] == b[sortBy]) return 0;
 return (a[sortBy] < b[sortBy]) ? -1 : 1;
    }
    return (a[sortBy] < b[sortBy]) ? -1 : 1;
}; 

// sort text desc
function sortTextDesc(a,b){
    var sortBy = $.fn.microView.sortedBy;
    if(a[sortBy] == b[sortBy]){
 if(a[sortBy] == b[sortBy]) return 0;
 return (a[sortBy] > b[sortBy]) ? -1 : 1;
    }
    return (a[sortBy] > b[sortBy]) ? -1 : 1;
};

Keine Kommentare:

Kommentar veröffentlichen

Socialize!