Using more than one variable for filtering in Vue.js

I've been busy working on implementing table filtering in Vue.js. So far, I have successfully filtered the table by name and date. However, I'm now facing a challenge with adding another filter along with them.

If you want to check out my current progress, feel free to visit this CodePen link.

This is how my computed property looks like:

filterItem() {
  let filterClient = this.selectedClient;
  let startDate = this.localizeDate(this.startDate);
  let endDate = this.localizeDate(this.endDate);
  let filterBranch = this.selectedBranch;

  const itemsByClient = filterClient
    ? this.salesReport.filter((item) => item.client_name === filterClient) && item.business_branch=== filterBranch)
    : this.salesReport;

  return itemsByClient.filter((item) => {
    const itemDate = new Date(item.date);
    if (startDate && endDate) {
      return startDate <= itemDate && itemDate <= endDate;
    }
    if (startDate && !endDate) {
      return startDate <= itemDate;
    }
    if (!startDate && endDate) {
      return itemDate <= endDate;
    }
    return true;
  });
},

Currently, it works when both name and business branch are provided. However, I aim to enhance the functionality to allow for filtering data with or without a name.

For instance, if a client is selected, only the rows related to that client should be displayed. Similarly, if a branch is selected (leaving other fields empty), the table should show the rows associated with the chosen branch.

Answer №1

Create filter functions and chain them together for efficient filtering.

filterItems() {
  let clientFilter = this.selectedClient;
  let startDate = this.localizeDate(this.startDate);
  let endDate = this.localizeDate(this.endDate);
  let branchFilter = this.selectedBranch;

  const clientFilterFunction = (item) => clientFilter
    ? item.client_name === clientFilter
    : true;

  const branchFilterFunction = (item) => branchFilter
    ? item.business_branch === branchFilter
    : true;

  const dateFilterFunction = (item) => {
    const itemDate = new Date(item.date);
    if (startDate && endDate) {
      return startDate <= itemDate && itemDate <= endDate;
    }
    if (startDate && !endDate) {
      return startDate <= itemDate;
    }
    if (!startDate && endDate) {
      return itemDate <= endDate;
    }
    return true;
  };

  return this.salesReport
    .filter(clientFilterFunction)
    .filter(branchFilterFunction)
    .filter(dateFilterFunction);
}

If you need more complex filtering, such as filtering only for branches or clients, dynamically add filter functions like this:

  let report = this.salesReport;

  if(this.selectedClient) {
    report = report.filter(clientFilterFunction);
  }

  if(this.selectedBranch) {
    report = report.filter(branchFilterFunction);
  }

  report = report.filter(dateFilterFunction);

  return report;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Monitor the collection for changes before adding an item to the collection

When using ui-select multiple, I am facing an issue where I need to check the collection before ng-model="collection" is updated in order to ensure that the new value is not already present in it. Simply watching the collection does not solve this problem ...

Unable to generate a JSON string from the JavaScript object

I need help converting the object I receive from the server into a JSON file for use in a d3.js chart: data = { "dog ":"5", "cat ":"4", "fish ":"12", } The desired output is: { "name" : "animal", "children" : [ {"name":"dog" ...

The Vue conditional event handling with the v-on directive and the prevent modifier

Is there a way to utilize the .prevent modifier of v-on dynamically? <a href="#" class="modal-overlay" aria-label="Close" v-on="overlayClickClosesModal ? { click: () => closeModal() } : {}" /> I'm attempting to prevent the URL from ...

Retrieve the processed data from a file using node.js

I have successfully read and parsed my file, however I am facing an issue with retrieving the output string. I want to access this string from a variable assigned to it on the client side. Despite using async series to handle callback functions effective ...

Add a npm module without type definitions

I am currently utilizing Typescript version 2.1 and facing an issue with installing an npm package called 'reactable' that lacks typings. When attempting to import the package using import * as Reactable from 'reactable', Typescript di ...

Encountering Challenges when Implementing Next.js with Jest

When attempting to run a test in next.js using jest, an error keeps appearing: The issue may be due to the wrong test environment being used. Refer to https://jestjs.io/docs/configuration#testenvironment-string for more information. Consider utilizing the ...

What is the process for obtaining the indirect link of a Google search result?

I am looking to obtain the indirect link of a Google search result. After performing a search on Google, if I right-click on the result link, it changes to something like this: https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&am ...

What is the best way to arrange the keys of a JavaScript object in a customized

I am struggling to find a way to custom sort a JavaScript object properly. For example, I have the following object: var test = { 'yellow': [], 'green': [], 'red': [], 'blue': [] } And an array with values ...

The swap feature in drag-and-drop does not have a defined function

I am currently developing a to-do app that utilizes drag and drop functionality to reorder items in the list. However, I have encountered an issue where swapping elements works perfectly for the first five elements but throws errors when dealing with the s ...

Efficient Ways to pass information to an Object within a nested function

const http = require('https'); exports.ip = async (req, res) => { const ip = req.body.ip; const ip_list = ip.trim().split(' '); const count = ip_list.length; var execution_count = 0; var success = {}; // **Creati ...

Mastering the art of customizing classes and styles in material-ui (React)

I am facing a challenge with version 1.2.1 of material-ui. My goal is to make the AppBar component transparent by overriding its styles as per the documentation here. This is the code snippet I have been working on: import React, { Component } from ' ...

"Notification: The marker element has been eliminated" encountered while attempting to restore text ranges using Rangy within a Vue component

I have a rather intricate Vue component that includes a contenteditable div. My goal is to highlight words within this div using the Rangy library and add extra markup while retaining this markup even after editing the text. Initially, I planned on asking ...

Ways to address the npm error: Missing script 'dev'

After successfully installing Node.js, I proceeded to install cnpm using the following command: npm install -g cnpm --registry=https://registry.npm.taobao.org cnpm install However, when I attempted to run the command cnpm run dev, an error occurred: npm ...

Error message: Uncaught TypeError - Unable to retrieve data using POST method in react with node and express servers

I am currently working on creating a Login / Register form using react for the client-side and node / express / (mongo) for the backend. The backend functionality is working smoothly as expected, with successful storage of credentials in the database upon ...

What is the method for determining the angle between two planes?

My question is about calculating the angle between two planes. Is it also possible to calculate the angle between two Object3D points like we do with planes? If you need a visual example, check out this fiddle: https://jsfiddle.net/rsu842v8/1/ const ...

Struggling to pass express.js router requests and responses to a class method

I am struggling with setting up an Express JS router. I am facing difficulty passing req and res to my class method. Not Working app.get('/', controller.index) Working app.get('/', (res,req) => controller.index(req,res) The routi ...

Ways to retrieve the chosen option from a dropdown menu within an AngularJS controller

I have a drop down (combo box) in my application that is populated with values from a JSON array object. Can someone please explain how to retrieve the selected value from the drop down in an AngularJS controller? Appreciate the help. ...

Developing Angular 2 custom async validators for use in reactive forms

I am currently working on a reactive form that requires unique form controls: this.form = new FormGroup({ name: new FormControl(this.initialValue, [ Validators.required, ], this._uniqueNameValidator.bind(this)), }); To achieve this, I have create ...

Issues detected between Angular and Express rendering operations

Having an issue with my angular code. It runs perfectly on its own, but when I try to access it on localhost with express, it only displays the HTML file. Here's my server code: var express = require('express'), app = express(); app ...

Determining the elapsed time using Momentjs

I need assistance with a NodeJS project where I am trying to determine if a specific amount of time (like 1 hour) has passed since creating an object. My project involves the use of MomentJS. For example, if moment(book.createdAt).fromNow() shows 2 hours ...