Tables can also be filtered by their numerical columns. For example, given a table where each row is a person and one of the columns contain data about the person's age, we might need to filter this table by specifying the age range. To do this, we use range filters.
We're going to assume that we're using the code and data from the Creating a sortable paginated table recipe. We have a list of people with their age displayed in a sortable, paginated table using the DataTables jQuery plugin. We will copy the files from the recipe and then add some extra filtering code.
The data that we need to filter is already available in the tableData
global variable; we can filter this data and then use the tableSetData
global function to display the filtered table.
The filter is going to work on the Age field.
Let's modify the previous code to add range filters to our table:
In the
index.html
file from the previous recipe, add two input elements after the opening<body>
tag:Age: <input id="range1" type="text"> to <input id="range2" type="text"> <br>
Add a script element for
filter.js
before the closing</body>
tag:<script type="text/javascript" src="filter.js"></script>
Finally, we create our
filter.js
script:(function() { function number(n, def) { if (n == '') return def; n = new Number(n); if (isNaN(n)) return def; return n; } function rangeFilter(start, end, col) { var start = number(start, -Infinity), end = number(end, Infinity); return function filter(el) { return start < el[col] && el[col] < end; } } $("#range1,#range2").on('change keyup', function() { var filtered = window.myTable.data.filter( rangeFilter($("#range1").val(), $("#range2").val(), 2)); window.myTable.setData(filtered); }); }());
The easiest way to filter array data is to use JavaScript's built-in Array.filter
function. This is a higher-order function; its first argument is a function that takes a row argument and returns true
if the row is to be added to the filtered array or false
if the row is to be left out.
To provide such a function, we create our own higher-order function. It takes the start and end ranges and the specified column. The return result is a function that filters every row.
To ignore empty or invalid values from the input, we use the number function. If the input field is empty or contains non-number data, a default value is provided (-Infinity
for the start of the range and +Infinity
for the end). This also enables us to do one-sided range filtering.
The Array.filter
function returns an array of all the elements that pass the filter. We display this array in our table.