|
| 1 | +/** |
| 2 | + * Sorts columns by any number, ignoring text. This plugin is useful if you have |
| 3 | + * mixed content in a column, but still want to sort by numbers. Any number means |
| 4 | + * |
| 5 | + * - integers, like 42 |
| 6 | + * - decimal numbers, like 42.42 / 42,42 |
| 7 | + * - signed numbers, like -42.42 / +42.42 |
| 8 | + * - scientific numbers, like 42.42e+10 |
| 9 | + * - illegal numbers, like 042, which is considered as 42, |
| 10 | + * - currency numbers, like €42,00 |
| 11 | + * |
| 12 | + * Plain text is ignored; columns with no recognizable numerical content |
| 13 | + * is pushed to the bottom of the table, both ascending and descending. |
| 14 | + * |
| 15 | + * @demo http://jsfiddle.net/vkkL5tv7/ |
| 16 | + * |
| 17 | + * @name Any number |
| 18 | + * @summary Sort column with mixed numerical content by number |
| 19 | + * @author [david konrad](davidkonrad at gmail com) |
| 20 | + * |
| 21 | + * @example |
| 22 | + * $('#example').dataTable( { |
| 23 | + * columnDefs: [ |
| 24 | + * { type: 'any-number', targets : 0 } |
| 25 | + * ] |
| 26 | + * } ); |
| 27 | +
|
| 28 | + * |
| 29 | + */ |
| 30 | + |
| 31 | +_anyNumberSort = function(a, b, high) { |
| 32 | + var reg = /[+-]?((\d+(\.\d*)?)|\.\d+)([eE][+-]?[0-9]+)?/; |
| 33 | + a = a.replace(',','.').match(reg); |
| 34 | + a = a !== null ? parseFloat(a[0]) : high; |
| 35 | + b = b.replace(',','.').match(reg); |
| 36 | + b = b !== null ? parseFloat(b[0]) : high; |
| 37 | + return ((a < b) ? -1 : ((a > b) ? 1 : 0)); |
| 38 | +} |
| 39 | + |
| 40 | +jQuery.extend( jQuery.fn.dataTableExt.oSort, { |
| 41 | + "any-number-asc": function (a, b) { |
| 42 | + return _anyNumberSort(a, b, Number.POSITIVE_INFINITY); |
| 43 | + }, |
| 44 | + "any-number-desc": function (a, b) { |
| 45 | + return _anyNumberSort(a, b, Number.NEGATIVE_INFINITY) * -1; |
| 46 | + } |
| 47 | +}); |
| 48 | + |
| 49 | + |
0 commit comments