Utilizing Vue JS for applying multiple filters on a single array

I'm currently facing challenges in optimizing my code. I've successfully created dynamically generated objects from an array, implemented a search function, and had a working filter (just one) at some point. However, my attempt to chain the filters failed unexpectedly. I need the ability to search and filter the array based on user choices among three categories: topic, price, and review stars. The selection could be one, two, or all of them.

Struggling with this problem has consumed most of my last 12 hours! I have no clue how to proceed given my implementation :/ Here is the main part of the code:


            let classes = {
                // Array objects here
            };
            // Vue instance here
            

            <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
            <div id="searchBar">
                <!-- Code for search bar interface -->
            </div>
        

Answer №1

You have the option to customize the filterAry function in order to evaluate each filter condition individually as illustrated below

let classes = {
  menu: [
    { topic: 'math', location: 'adadadas', price: 80, length: "120", time: "9:00", reviewStars: "3" },
    { topic: 'math', location: 'dsadassa', price: 90, length: "70", time: "11:00", reviewStars: "4" },
    { topic: 'math', location: 'dadass', price: 120, length: "30", time: "14:00", reviewStars: "1" },
    { topic: 'english', location: 'dasdsadas', price: 110, length: "45", time: "13:00", reviewStars: "2" },
    { topic: 'english', location: 'fsafasf', price: 90, length: "75", time: "11:00", reviewStars: "4" },
    { topic: 'english', location: 'fafasa', price: 90, length: "100", time: "17:00", reviewStars: "2" },
    { topic: 'english', location: 'fsasada', price: 130, length: "90", time: "15:00", reviewStars: "3" },
    { topic: 'piano', location: 'dsadsadsads', price: 120, length: "", time: "50", time: "13:00", reviewStars: "4" },
    { topic: 'piano', location: 'dsadasddsadsadas', price: 140, length: "40", time: "12:00", reviewStars: "1" }
  ],
  input: {
    topic: '',
    location: 'All',
    topics: 'All',
    price: 'All',
    reviews: 'All'
  },
  newAry: [],
  otherAry: [],
  filterText: null
};


var searchBar = new Vue({
  el: '#searchBar',
  data: classes,
  computed: {
    menuArray() {
      let vm = this
      let array = new Set()
      vm.menu.forEach(function (item) {
        array.add(item.location)
      })
      console.log(array)
      return vm.newAry = Array.from(array)

    },

    // More computeds...

    filterAryTopic() {
      let vm = this
      if (vm.input.topic) {
        // Handling logic for filtering by topic
      } else {
        // Return default if no topic is provided
      }

    },

    // More filters...

    filterAry() {
      let vm = this
      // Complete logic for filtering based on all criteria
    },


    getAry() {
      let vm = this
      return vm.otherAry
    }
  },
  mounted: function () {
    newAry = classes;
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="searchBar">
    <div class="display-3 text-center my-5 text-secondary">Activities!  </div>
    <div class="container w-75">
      <div class="row mb-3">
        <div class="col-md-4">
          <div>
            <select name=""  class="form-control" v-model.trim="input.price">
              <option value="All" selected>All</option>
              <option :value="item" v-for="item in menuArrayPrice">{{item}}</option>
            </select>
            <select name=""  class="form-control" v-model.trim="input.topics">
              <option value="All" selected>All</option>
              <option :value="item" v-for="item in menuArrayTopic">{{item}}</option>
            </select>
            <select name=""  class="form-control" v-model.trim="input.reviews">
              <option value="All" selected>All</option>
              <option :value="item" v-for="item in menuArrayReview">{{item}}</option>
            </select>
          </div>
        </div>
        <div class="col-md-8">
          <input type="text" name=""  class="form-control" v-model.trim="input.topic" placeholder="search topics">
        </div>
      </div>
    </div>

    <div class="container w-75 mb-5">
      <div class="row">
        <div class="col-md-4" v-for="item in filterAry" >
          <ul class="course list-group mb-3">
            <li class="list-group-item text-accent h4 font-weight-bold">{{item.location}}</li>
            <li class="list-group-item text-secondary song-item d-flex flex-column ">
              {{item.topic}}{{item.price}}
          </ul>
        </div>
      </div>
    </div>
  </div>

Answer №2

It appears that you've made an attempt here, but I believe a fresh perspective is needed. The correct approach would be to chain filters and ensure they are working correctly with your dataset.

This type of architecture might be more appropriate:

data() {
  return {
    topic: 'All',
    location: 'All',
    // and other filterable parameters
  }
},

computed: {
    filteredAry () {
      const { topic, location } = this
      let filteredMenu = Array.from(menu);
      
      if (topic !== 'All') {
        filteredMenu = filteredMenu.filter(item => item.topic === topic)
      }
      // ... repeat for all possible filter values
      return filteredMenu
    },
  },

You can then utilize filteredAry in your v-for loop to display the data.

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

Tips for efficiently serving a static file without triggering a disk read

res.sendFile is the preferred method for serving a static file in express. However, it appears that res.sendFile reads the file from disk with each request, as shown below: router.get('/', (req, res) => { res.sendFile('./guest.js&apo ...

Exploring the Ins and Outs of Debugging JavaScript in Visual Studio Using

I encountered a peculiar issue while testing some code. When the program is executed without any breakpoints, it runs smoothly. However, if I introduce a breakpoint, it halts at a certain point in the JSON data and does not allow me to single-step through ...

Using the same Vue component instance on different routes

I'm currently working on a Vuejs app where each page is rendered based on the route. For example: route = /, Component = Main.vue <template> <div> <toolbar :user="user"></toolbar> <app-content></app-conten ...

Delivering VueJS Builds via Express.js by leveraging history mode

I am trying to find a way to serve vue js dist/ through express js while using the history router in my vue js app. Here are some of the API calls I need: api/ s-file/sending/:id terms/get/:which I came across a Python solution on Github, but I'm ...

Generate text in a random spot effortlessly

After doing some research on various development platforms, I stumbled upon this JSFiddle that seems to have a solution for my requirements. The only thing missing is the ability to input a specific word (without user input) and automate the process at fix ...

Troubleshooting problems with Window.postMessage()

When attempting to fetch data from different domains, I am facing an issue. However, if I run the code on the same server, everything works perfectly fine and I am able to retrieve the message. index.html: <head> <title>Test 1</title&g ...

The functionality of the Checkbox is experiencing issues when used in conjunction with Bootstrap 5 and Vuejs

Here is a div showcasing an input with its label. However, there seems to be an issue where I am unable to click on the checkboxes. This code snippet serves as an illustration of utilizing Bootstrap 5 checkboxes within VueJs. <ul class="widget-lis ...

What is the correct method for asynchronously loading CSS files in web development?

On a mission to enhance my website's performance, I set out to achieve the perfect score on PageSpeed Insights. Everything was going smoothly until I encountered an issue with CSS delivery. I initially achieved a flawless result by utilizing the prel ...

Sending a value to a different Ionic page based on a specific condition

Here is the code snippet from my app.js: var app = angular.module('dbpjkApps', ['ionic']) app.controller('kategoriCtrl', function($scope) { $scope.listKat = [ {kat: 'math'}, {kat: 'physics'}, ...

Rendering React Router server-side with client-side session information

Currently, I am working with mozilla client-sessions in conjunction with express/node. My goal is to pass my session.user to the react-router within a standard * request. Despite my efforts and attempts, I keep encountering an issue where it becomes unde ...

What is the best method for integrating addEventListener with Javascript functions located in a different file?

I currently have document.addEventListener('DOMContentLoaded', functionName); which uses the function below: function functionName() { $.ajax({ type: 'GET', url: '/populatePage', success: function(data) { ...

Performing a Search Operation using AJAX with Elasticsearch

I've been struggling to find the correct method for requesting data from elasticsearch using a jQuery AJAX call. I keep encountering parsing errors or getting all documents in the index instead of my intended results. $(document).ready(function() ...

Preserve the original position of the inner <div> when animating the container <div> using JQuery

I am currently working on a small website and encountering some challenges with jQuery animation. My issue involves placing a single character text inside a circle and wanting it to grow when the user hovers over it, while keeping the inner text in its ori ...

Is there a way to select and handle multiple elements using async wdio with the same selector?

My test scenario involves using async wdio to test my React app, where I need to count elements with a specific selector and check their contents. The code snippet being tested is as follows: <div className='container'> <li className= ...

Transforming a solitary JSON object into a JSON array using PHP

i am making a request to coincap.io for a single JSON object {"altCap":282255454377.94916,"bitnodesCount":11508,"btcCap":149160858393,"btcPrice":8830.18849156212,"dom":63.86,"totalCap":431416312770.94904,"volumeAlt":709387849.4057536,"volumeBtc":12537293 ...

Clearing a textarea in jQuery

I'm experiencing an issue that I can't seem to resolve on my own. Any assistance would be greatly appreciated. My function designed to clear a textbox upon click doesn't seem to be working correctly: $(function() { $('textarea#co ...

AngularJS: Modifying directive according to service value update

In my current application, I have a basic sidebar that displays a list of names fetched from a JSON call to the server. When a user clicks on a name in the sidebar, it updates the 'nameService' with the selected name. Once the 'nameService& ...

Leverage the Ajax response within a Jade template

I'm currently utilizing ExpressJS with the Jade template engine. My goal is to achieve the following: Within a Jade file, I need to extract a variable that will be used in a JavaScript file. This JavaScript file will then make an Ajax request to the ...

The image located at 'http://localhost:8080/favicon.ico' was unable to load due to a violation of its content

I am currently developing a JavaScript app called food2fork. I encountered an issue when the AJAX call API promise is fulfilled and the results (recipes) are rendered. However, when I click on one of the recipes, it moves to the next page and displays: ...

The passing of query string parameters from JavaScript to a PHP processing script is ineffective

I am looking to dynamically populate a jQWidgets listbox control on my webpage with data retrieved from a MySQL database table once the page has finished loading and rendering. PARTIAL SOLUTION: You can find a solution here. NEW PROBLEM: I have created a ...