import { KettalTableAdvancedFilters } from "../../../types/KTable"; /** Function that filters the table * * @param {List} rows List of rows to be filtered * @param {List} filters List of filters set by user * * @public */ function filterRows(rows: any[], filters: KettalTableAdvancedFilters) { let keys = Object.keys(filters); // If there is a null object, it is deleted for (let i = 0; i < keys.length; i++) { if (filters[keys[i]] === null) { delete filters[keys[i]]; } } // Get the list of keys keys = Object.keys(filters); // Filter the rows, if a row doesn't contain the specified value on each filter, it's ignored return rows.filter(function (row) { for (let j = 0; j < keys.length; j++) { const filterValue = filters[keys[j]]; const rowValue = row[keys[j]]; // Skip null/undefined/empty filter values if (filterValue === null || filterValue === undefined) continue; // If is type option (array) if (Array.isArray(filterValue)) { if (filterValue.length === 0) continue; // Use Array.prototype.some() to check if any element in the array matches the row's value if ( filterValue.some((val) => { return String(rowValue) .toLowerCase() .includes(String(val).toLowerCase()); }) ) { continue; // If any element matches, move to the next key } else { return false; // If none of the elements match, return false } } // If is type boolean if (typeof filterValue === "boolean") { if (filterValue !== rowValue) return false; continue; } // If boolean can have intermediate value, show all rows if (filterValue === "null") { continue; } // Convert both values to string for comparison (works for string, number, decimal, date, dateTime) const rowValueAsString = typeof rowValue === "string" ? rowValue : String(rowValue); const filterValueAsString = typeof filterValue === "string" ? filterValue : String(filterValue); // If the value doesn't match, return false if ( !rowValueAsString .toLowerCase() .includes(filterValueAsString.toLowerCase()) ) { return false; } } return true; // If all conditions are met, return true }); } export default filterRows;