filter()
Create a new API instance with all elements from the result set which pass a given test.
Description
The filter()
method provides a way of filtering out content in an API instance's result set which does not pass the criteria set by the provided callback method. This method should not be confused with search()
which is used to search for records in the DataTable - i.e. the filter method does not change the rows that are displayed in the DataTable.
When working with the plural methods such as rows()
and columns()
you may wish to use the eq()
utility method to reduce the API instance from a 2D array to a 1D array which can be iterated over using this method.
This method makes use of the fact that DataTables API objects are "array like", in that they inherit a lot of the abilities and methods of the Javascript Array
type.
In this case, this method is a proxy for the Javascript Array.prototype.filter
method and is provided as a utility method for the DataTables API. For more information about the original method, please refer to the Mozilla MDN documentation for filter
. In browsers which do not support filter
natively, a polyfill is provided to allow this DataTables method to operate as expected.
Type
function filter( fn )
- Description:
Iterate over the result set of an API instance and test each item, creating a new instance from those items which pass.
- Parameters:
Name Type Optional 1 fn
No Callback function which is called for each item in the API instance result set. The callback is called with three parameters:
- The element value
- The element index in the result set
- The API instance being traversed
The callback should return
true
if the value is to be included in the new instance's own result set, and false otherwise.- Returns:
New API instance with the values from the result set which passed the test in the callback.
Examples
Filter data from a column, to just the data that is greater than 20:
var table = new DataTable('#myTable');
var filteredData = table
.column(0)
.data()
.filter(function (value, index) {
return value > 20 ? true : false;
});
Filter data from multiple columns, getting the data points which are greater than 20 from the cells in both columns:
var table = new DataTable('#myTable');
var filteredData = table
.columns([0, 1])
.data()
.flatten()
.filter(function (value, index) {
return value > 20 ? true : false;
});