title: How to filter an array by several params only if they are present
body: <p>I have a function to filter results by several params, such as <code>name</code>, <code>status</code>, <code>type</code> and date range (<code>startDate</code> and <code>endDate</code>). I would like to be able to filter results by these params together, but only if they are present, i. e. I can pass <code>name</code> and <code>status</code>, but don't pass <code>type</code>. I don't know how to do this with a date range. Now the filter is working only if I pass <code>startDate</code> and <code>endDate</code>, 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 <code>startDate</code> and <code>endDate</code> optional?</p>
  <p>Here is my filter:</p>
  <pre><code>if (params.name || params.status || params.type || params.startDate &amp;&amp; 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) =&gt;
        data.name.match(new RegExp(params.name, 'ig')) &amp;&amp;
        data.status.includes(params.status || '') &amp;&amp;
        data.type.includes(params.type || '') &amp;&amp;
        (
          new Date(data.createdAt).getTime() &gt; startDate &amp;&amp; new Date(data.createdAt).getTime() &lt; endDate
        )
    );
  }
  </code></pre>
  <p>Thank you for your help!</p>
  <p><strong>EDIT</strong>:</p>
  <p>I'm using this filter inside a function on backend:</p>
  <pre><code>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 &amp;&amp; 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) =&gt;
          data.name.match(new RegExp(params.name, 'ig')) &amp;&amp;
          data.status.includes(params.status || '') &amp;&amp;
          data.type.includes(params.type || '') &amp;&amp;
          (
            new Date(data.createdAt).getTime() &gt; startDate &amp;&amp; new Date(data.createdAt).getTime() &lt; endDate
          )
      );
    }
  
    const result = {
      data: dataSource,
      success: true,
    };
  
    return res.json(result);
  }
  </code></pre>