Jon Dosmann
Jon Dosmann

Reputation: 737

Sorting by part of a number in datatables

I have a DataTable where my first column is a VIN number.

Example: FLXVU3822G1000013

Now VIN numbers are just a bunch of information tacked together. The last 6 numbers are the sequence number for that year. You can see that this example vehicle is the 13th one of the year. I'd really like to have my list filtered on those last 6 digits. Is there a way to do that?

Upvotes: 1

Views: 271

Answers (1)

davidkonrad
davidkonrad

Reputation: 85578

You can easily solve this by a custom sorting plugin. In fact you just need to extract the last 6 digits and return them as a number, then dataTables will sort the column using the internal number sorting algorithm :

jQuery.extend( jQuery.fn.dataTableExt.oSort, {
 "last-6-digits-pre": function ( a ) {
    var n = a.substring(a.length - 6, a.length)
    return parseInt(n)
 }
})

Usage :

var table = $('#example').DataTable({
  columnDefs : [
     { targets: 0, type: 'last-6-digits' }
  ]
})  

where targets: 0 is the index of the column you want to be sorted this particular way.

See demo -> http://jsfiddle.net/zhmcLkb9/

Upvotes: 2

Related Questions