Cork Kochi
Cork Kochi

Reputation: 1891

Datatables Sorting For Alphanumeric Column

I am using Datatables for Sorting the ID column.

ID

MPT123

RST789

AZE190

How can I sort this based on Numeric Values I tried by doing

"columnDefs": [{
            targets: "datatable-nosort",
            orderable: false,
            bsort: false,
            sType: "numeric"
}]

But this didn't worked.

Upvotes: 1

Views: 1432

Answers (2)

Jitesh Sojitra
Jitesh Sojitra

Reputation: 4043

I'm using natural sorting JS and works great - https://datatables.net/plug-ins/sorting/natural#Example

Sort data with a mix of numbers and letters naturally. Data can often be a complicated mix of numbers and letters (file names are a common example) and sorting them in a natural manner is quite a difficult problem.

Fortunately a deal of work has already been done in this area by other authors - the following plug-in uses the naturalSort() function by Jim Palmer to provide natural sorting in DataTables.

Upvotes: 0

Cork Kochi
Cork Kochi

Reputation: 1891

I got it working , posting the working code

jQuery.extend( jQuery.fn.dataTableExt.oSort, {
"formatted-num-pre": function ( a ) {       
    a = (a === "-" || a === "") ? 0 : a.replace( /[^\d\-\.]/g, "" );
    return parseFloat( a );
},

"formatted-num-asc": function ( a, b ) {
    return a - b;
},

"formatted-num-desc": function ( a, b ) {
    return b - a;
}
} );

And call the method as

{ "type": "formatted-num", targets: 0 }]

Upvotes: 1

Related Questions