简体   繁体   中英

How to apply filter on data from a jquery datatable?

I have a jquery datatable which I am showing on UI. I want to apply filter on the datatable data and store the filtered data into a variable (not looking for filtering the data on UI).

I tried the below code but it returns the same rows as that of the original datatable.

var filteredData = $('#table').DataTable().column(1).filter( function ( value, index ) {
        return value == 'test' ? true : false;
    } ).data();
$('#table').DataTable().column(1).filter( function ( value, index ) {
        console.log("VALUE: " + value);
        console.log("INDEX: " + index);
    } ).data();

This is showing next, is not correct:

VALUE: 1 INDEX: 0

So... change to this:

var filteredData = $('#table').DataTable().column(1).data().filter( function ( value, index ) {
  return value=="P";
}).toArray();

console.log("FILTERED DATA: " + filteredData);

This is showing next:

FILTERED DATA: P,P

As you can see, this only stores the column that you are filtering... If you want to store other column (and in general), I would use this other method ( Reference ):

var array = [];

$('#table').DataTable().rows().every( function ( rowIdx, tableLoop, rowLoop ) {
    var data = this.data();
    if (data[1] == "P"){
        array.push(data[5])
    }
    // ... do something with data(), or this.node(), etc
} );

console.log(array);

As you can see, this stores the value of column 5 filtering by column 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM