What is the method for applying multiple criteria to filter an array in Vuejs?

const app = new Vue({
  el: '#app',
  data: {
    search: '',
    itemsList: [],
    isLoaded: false,
    selectNum: status,
    userList: [{
        id: 1,
        name: "Prem",
        status: "ok"
      },
      {
        id: 2,
        name: "Chandu",
        status: "notok"
      },
      {
        id: 3,
        name: "Shravya",
        status: "ok"
      },
      {
        id: 4,
        name: "kirt",
        status: "notok"
      }
    ]
  },
  created() {
    vm.itemsList = [];
    vm.isLoaded = true;
  },
  computed: {
    filteredAndSorted() {
      // function to compare names  
      function compare(a, b) {
        if (a.name < b.name) return -1;
        if (a.name > b.name) return 1;
        return 0;
      }

      return this.userList.filter(user => {
        return user.name.toLowerCase().includes(this.search.toLowerCase()) &&
          user.status === this.selectNum
      }).sort(compare)
    }
  }
})
<div id="app">
  <div v-if="isLoaded">
    <select v-model="selectNum" name="text">
      <option :value="status">ok</option>
      <option :value="status">notok</option>
    </select>
  </div>
  <div class="search-wrapper">
    <input type="text" v-model="search" placeholder="Search title.." />
    <label>Search Users:</label>
  </div>
  <ul>
    <li v-for="user in filteredAndSorted">{{user.name}}</li>
  </ul>
</div>

I am working on implementing a feature,

Initially, the array will be populated using v-for. At the top, there are two options, a search bar and a dropdown. With these options, I aim to filter the array.

The search bar is meant to filter the array values. The dropdown is used to filter the status of each element in the array.

Answer №1

Check out this code example:

const app = new Vue ({
  el: '#app',
  data() {
    return {
      search: '',
      itemsList: [],
      isLoaded: false,
      selectNum: '',
      userList: [
        {
          id: 1,
          name: "Alice",
          status:"ok"
        },
        {
          id: 2,
          name: "Bob",
          status:"notok"
        },
        {
          id: 3,
          name: "Charlie",
          status:"ok"
        },
        {
          id: 4,
          name: "David",
          status:"notok"
        }
      ]
    }
  },
  created(){
    this.isLoaded = true;
  },
  computed: {
    filteredAndSorted(){
     function compare(a, b) {
       if (a.name < b.name) return -1;
       if (a.name > b.name) return 1;
       return 0;
     }
     const res = this.userList.filter(user => {
          return user.name.toLowerCase().includes(this.search.toLowerCase())
       }).sort(compare)
     if (this.selectNum) {
       return res.filter(user => user.status === this.selectNum )
     }
     return res
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-if="isLoaded">
    <select v-model="selectNum" name="text"> 
      <option value="" selected="selected">Select status</option>
      <option value="ok">ok</option>
      <option value="notok">notok</option>
    </select>
  </div>
  <div class="search-wrapper">  
    <input type="text" v-model="search" placeholder="Search title.."/>
        <label>Search Users:</label>
  </div>  
  <ul>
    <li v-for="user in filteredAndSorted">{{user.name}}</li>
  </ul>
</div>

Answer №2

An error occurred in the code on line 25.

// ...
  created(){
    var vm = this;
    vm.itemsList = [];  // => j is undefined
    vm.isLoaded = true;
  },
// ...

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

Error in ng-repeat loop: detecting duplicates when none are present

$scope.subjects = [ "Computer Security", "Graphics and Multimedia", "Networks", "Computer Science and Engineering", "Game Design", "Programming", "Information Technology", "Software Engineering", "Technology Manageme ...

Implementation of multiple angular guards causing a crash on the page

I have been attempting to implement separate guards for distinct pages. Essentially, I am checking a boolean parameter to determine if a user is logged in or not. Below are the two guard.ts codes that I am using: export class IsAuthenticatedGuard implemen ...

"Implementing a JavaScript function to dynamically add multiple div elements to a

I am just starting to learn JavaScript. The main div with the ID "row_logic" contains two nested divs. I need help figuring out how to dynamically increment this root div in the format shown below using JavaScript. <div class="row-fluid" id="row_log ...

Is there a way to retrieve the value from an input box?

<td class="stockQuantity"> <input class="form-control" id="Cart1" name="qty_req" required="required" type="text" value=""><br> <button type="button" o ...

Exploring jQuery's selection techniques involving filtering and excluding elements

How can I select all elements with the class .Tag that are not equal to the element passed to the function? Here is my current attempt: $("a.tag").filter(":visible").not("\"[id='" + aTagID + "']\"").each( function place(index, ele ...

Is `send()` considered an anonymous function?

I am testing ajax on a local server, but encountering an issue where the console is showing that send() is being identified as an anonymous function and I am receiving a blank document. The console displays: XHR finished loading: GET "http://localhost/js ...

Is there any way to extract the source files from a compiled Electron application?

Is there a way to extract the contents of a .app Application developed using Electron for Mac OS? I'm eager to explore the underlying source files, but I'm not familiar with the procedure to access them. Any assistance would be greatly appreciate ...

accessing a webpage using an ionic application

I currently have a responsive website, but I am looking to turn it into an app in order to utilize push notifications. Right now, I am using the inappbrowser plugin to open my website with this code: <a href="#" onclick="window.open('http://www.ex ...

When the button is clicked, request the total count of elements in the array

Is there a way to log the index of an array element when clicked? I have a large array with over 100 elements: var cubesmixed = []; var cubes; for(var i = 0; i < 143; i++) { cubes = paper.rect(Math.floor(Math.random()*2000), Math.floor(Math.random ...

How to perfectly position an image within a fixed full screen container

When you click on a thumbnail image, a full-screen overlay with a larger version of the image will be triggered using JavaScript. To ensure that the image is centered and resized inside the black overlay when the browser window size changes, I attempted t ...

What is the best way to retrieve the values of "qty" and "price" and access them within the item [array] without knowing the IDs?

I am currently working on a shopping cart project, specifically on the "previous orders" page to display order details. My goal is to output this information in an (.ejs) file. The data structure includes nested objects, and within one object, propertie ...

When you hover over the button, it seamlessly transitions to a

Previously, my button component was styled like this and it functioned properly: <Button component={Link} to={link} style={{ background: '#6c74cc', borderRadius: 3, border: 0, color: 'white', height: 48, padding: '0 ...

Leverage and repurpose OOP objects

I am exploring how to inherit from Button using prototypes. Despite my efforts, the alerted name remains "Sarah" as it is the last Child created. I believe the Creator Class should be responsible for setting the name using a Method in Button. Check out m ...

Is there an equivalent of HtmlSpecialChars in JavaScript?

It seems that finding this is proving more difficult than anticipated, even though it's such a simple concept... Is there an equivalent function in JavaScript to PHP's htmlspecialchars? While it's possible to create your own implementation, ...

Encountering a 404 error when typing a link and refreshing the page in Laravel combined with VueJS

I encountered an issue while working on a Laravel VueJS application for our Proof of Concept (POC). I have integrated vue-router into the project and it is functional. However, whenever I attempt to navigate to a specific page defined in the routes of app. ...

Anticipating the resolution of promises and observables in Angular 2

Within my accountService module, there is a dialog prompt that requests the user's username and password, returning a promise. If the user clicks on close instead of dismissing the dialog box and the validators require the input data before allowing t ...

Can Keyboarddatepicker automatically format the date?

We are utilizing material ui Keyboarddatepicker in our React application and have specified the date format using props as format=DD/MMM/YYYY, resulting in dates being displayed like "10/12/2020". The date picker functions perfectly when selecting a date. ...

Tips for generating a fresh array by conditionally including an extra property based on the comparison of two arrays

I am working with two different arrays: lockers: [ { locker_id: 1, label: { size: 1, label: "small" } }, { locker_id: 2, label: { size: 3, label: "medium" } }, { locker_id: 3 ...

Just updated to Angular 10, encountered issue: Unable to modify the read-only property 'listName' of an object

After updating my Angular project from version 8 to version 10, I encountered an error while trying to edit an input field in a Material Dialog. The error message displayed is as follows: ERROR TypeError: Cannot assign to read only property 'listName& ...

Include images in the form of .png files within the td elements of a table that is dynamically generated in the index

I have successfully created a table using embedded JavaScript with the help of messerbill. Here is the code: <table id="Table1"> <tr> <th>Kickoff</th> <th>Status</th> <th>Country</th> < ...