I have a function to filter results by several params, such as name
, status
, type
and date range (startDate
and endDate
). I would like to be able to filter results by these params together, but only if they are present, i. e. I can pass name
and status
, but don't pass type
. I don't know how to do this with a date range. Now the filter is working only if I pass startDate
and endDate
, in all other cases, even if other params are present and there is corresponding data in the array, it returns null. How can I make startDate
and endDate
optional?
Here is my filter:
if (params.name || params.status || params.type || params.startDate && params.endDate) {
const startDate = new Date(params.startDate).setHours(0,0,0);
const endDate = new Date(params.endDate).setHours(23,59,59);
dataSource = tableListDataSource.filter(
(data) =>
data.name.match(new RegExp(params.name, 'ig')) &&
data.status.includes(params.status || '') &&
data.type.includes(params.type || '') &&
(
new Date(data.createdAt).getTime() > startDate && new Date(data.createdAt).getTime() < endDate
)
);
}
Thank you for your help!
EDIT:
I'm using this filter inside a function on backend:
function getRule(req, res, u) {
let realUrl = u;
if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
realUrl = req.url;
}
const params = parse(realUrl, true).query;
if (params.name || params.status || params.type || params.startDate && params.endDate) {
const startDate = new Date(params.startDate).setHours(0,0,0);
const endDate = new Date(params.endDate).setHours(23,59,59);
dataSource = tableListDataSource.filter(
(data) =>
data.name.match(new RegExp(params.name, 'ig')) &&
data.status.includes(params.status || '') &&
data.type.includes(params.type || '') &&
(
new Date(data.createdAt).getTime() > startDate && new Date(data.createdAt).getTime() < endDate
)
);
}
const result = {
data: dataSource,
success: true,
};
return res.json(result);
}