New sorting plugin - sort by any number, ignore text

New sorting plugin - sort by any number, ignore text

davidkonraddavidkonrad Posts: 13Questions: 4Answers: 0

I have made a new sorting plug-in that maybe could interest others, perhaps be included on the sorting plug-ins list.

sort-numbers-ignore-text sorts by any number, ignoring text in the columns.
Plain text columns are pushed to the bottom of the table. By any numbers means :

  • integers, like 66
  • decimal numbers, like 66.66
  • negative numbers, like -66.66 (+66.66 as well)
  • scientific numbers, like 66.66e+10
  • illegal numbers, like 066, which is considered as 66
function sortNumbersIgnoreText(a, b, high) {  
    var reg = /[+-]?((\d+(\.\d*)?)|\.\d+)([eE][+-]?[0-9]+)?/;     
    a = a.match(reg);  
    a = a !== null ? parseFloat(a[0]) : high;  
    b = b.match(reg);  
    b = b !== null ? parseFloat(b[0]) : high;  
    return ((a < b) ? -1 : ((a > b) ? 1 : 0));      
}  
jQuery.extend( jQuery.fn.dataTableExt.oSort, {  
    "sort-numbers-ignore-text-asc": function (a, b) {  
        return sortNumbersIgnoreText(a, b, Number.POSITIVE_INFINITY);  
    },  
    "sort-numbers-ignore-text-desc": function (a, b) {  
        return sortNumbersIgnoreText(a, b, Number.NEGATIVE_INFINITY) * -1;  
    }  
});  

code at github -> https://github.com/davidkonrad/datatables-sort-numbers-ignore-text
demo -> http://jsfiddle.net/6qmkY/

Answers

  • Adam84Adam84 Posts: 10Questions: 4Answers: 0

    Hi David,
    This sorting plugin is really useful. Can you suggest how you would modify the regular expression so that it will allow comma separated numbers?

  • ignignoktignignokt Posts: 146Questions: 4Answers: 39

    Looks pretty useful for the non server-side people. This is one reason I love using server-side for everything though. You have an INT in the database, and in your actual column it can be "I saved $1,572.89 on my car insurance!". Then when you sort, it still sorts by what is actually in the DB column, which is just 1572.89

This discussion has been closed.