Show the sorted list with various choices in Vue

I've been searching high and low, but I can't seem to find a solution to my issue. The closest answer I stumbled upon is here, however, it involves quite a bit of rework from what I currently have set up.

My goal is to filter an array based on multiple user inputs. While my demo only includes two inputs, the actual application will likely have around five. You can check out my progress so far on this JSFiddle.

HTML

<div id="app">
   <h2>Continent</h2>
   <div v-for="filter in filters.continent">
    <input type="checkbox" :value="filter" v-model="search.continent"> {{filter}}
   </div>

   <h2>Budget</h2>
   <div v-for="filter in filters.budget">
    <input type="checkbox" :value="filter" v-model="search.budget"> {{filter}}
   </div><br/>

   <p>You would like to live in {{search.continent}} and your budget is {{search.budget}}</p>

   <div v-for="country in filteredCountries">
    {{country.name}}
   </div>
</div>

JS

new Vue({
  el: "#app",
  data() {
    return {
        search: {
        continent: [],
        budget: []
      },

      filters: {
        continent: ['Europe', 'Asia', 'North America'],
        budget: ['Low', 'Medium', 'High'],
      },

      countries: [
        {
            name: "Sweden",
          continent: "Europe",
          budget: ["Medium", "High"],
        },
        {
            name: "Hong Kong",
          continent: "Asia",
          budget: ["Medium", "Low"],
        },
        {
            name: "Thailand",
          continent: "Asia",
          budget: ["Low"],
        },
        {
            name: "Canada",
          continent: "North America",
          budget: ["Medium", "High"],
        },

        {
            name: "US",
          continent: "North America",
          budget: ["Medium", "Low"],
        }

      ]
    }
  },

  computed: {
    filteredCountries: function(){
                return this.countries.filter((country) => 

                    this.search.budget.some(el => country.budget.includes(el)),



            )

            },
  }
})

In my actual app, I use different components for results and filters with an event bus that sends search data to the filtered computed property.

If anyone could provide guidance on how to achieve my desired outcome without adding complexity when more filter options are added, I would greatly appreciate it!

Edit: Baboo_'s response is almost there, but I realized I missed a couple of things after testing the fiddle. Firstly, the filters should be able to accept an array of options. I have updated my Fiddle to demonstrate this.

The intended behavior is for the filters to dynamically update the results like a sidebar filter. Although it's optional, I aim to include a hidden filter with everything checked by default. All other inputs should refine the results in real-time.

Answer №1

If you want to narrow down the list of countries based on budget and continent criteria, you can use the following approach:

computed: {
  filteredCountries: function(){
    return this.countries
     .filter(country => this.search.budget.includes(country.budget))
     .filter(country => this.search.continent.includes(country.continent));
  },
}

Check out this working example.

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

Creating immersive 3D sound experiences using Web Audio and Three.js

I have a panorama player with 3D sounds that I am trying to integrate into Three.js by following this tutorial: http://www.html5rocks.com/en/tutorials/webaudio/positional_audio/ The camera remains fixed, while the 3D sounds are positioned across the scene ...

Including a new server to the database while extending an invitation to a Discord server bot

My goal is to have the server information added to the mongoose database when a bot is added to the server. Here is the code snippet for the database: const mongoose = require('mongoose'); const PrefixSchema = new mongoose.Schema({ Prefix: ...

The quickest method in numpy for obtaining the distance of the product of n pairs within an array

I have a set of N points, represented by arrays such as: A = [2, 3] B = [3, 4] C = [3, 3] . . . These points are stored in a numpy array like this: arr = np.array([[2, 3], [3, 4], [3, 3]]) My goal is to calculate and output all pairwise distances in BFS ...

Concurrent Openlayers maps in Rails - A Viable Option

I've been playing around with Openlayers maps on my website. The map functionality is working perfectly, but I'm having trouble getting the maps to display correctly on my page. My goal is to show a map in each search result on my screen - one m ...

Tips for retrieving return values from AJAX URL content

As I am writing some code to send data from one page to another through the ajax URL, I encountered an issue where the retrieved values on the previous page are showing as null. The first page code looks like this: <script> function myFunction() { ...

Extracting values from multiple checkboxes and binding them to textboxes using VueJS

After reading a basic example of multiple checkboxes on Vue's Docs here, I understood how the selected checkbox values are added to an array. This functionality worked well for my project, but I needed something different. In my app, I wanted the abi ...

Error: A DOMException was caught in the promise while trying to push the router

Currently, I am facing an issue while working with React. An Uncaught DOMException occurs when trying to push the router. This exception specifically happens when I attempt to push a new URL into the router using an event triggered from a button in a mod ...

What is the best way to retrieve, organize, and showcase top commentators on a website using PHP and MySQL?

I've been trying for two days and I'm still stuck on this: What's the best way to fetch all users who have commented on a specific article, arrange them in descending order based on their comment count, and then show their usernames along wi ...

In JavaScript, a button is programmed with a rare 1.04% probability of directing to Page A and a much higher 98.96% likelihood of redirecting to Page

My goal is to create a button that, when clicked, will have a 1.04% probability of navigating to Page A and a 98.96% chance of going to Page B. The challenge I'm facing is in randomizing these results using JavaScript. I am fairly new to this language ...

NodeJS Like/Dislike System: Leveraging the Power of NodeJS

(Please refer to my solution in the answer post below) Hello there! Today, I have a question about implementing a like/dislike system using nodeJs with data stored in MongoDB. What is the current scenario? I'm tasked with creating the backend for ...

Difficulty arises when attempting to employ JSON.parse() on an array encoded utilizing PHP's json_encode() function

My Vue component retrieves data from Apache Solr, where the field I'm working with is an array generated using json_encode() in PHP. Here's my component method: data () { return { slideshow: {}, slides: {} } } ...

Unusual navigation patterns in Angular

https://i.sstatic.net/kdh4A.png My Mean app is set up with the Angular app residing in the '/dashboard' path. The home page of the app works fine. Reloading the app returns the page it was on. Even routes with '/dashboard/anything/anything& ...

Steps to resolve the "cannot get product" error on Heroku after submitting a value

view the image description hereI have been working on a MERN full stack project and everything was functioning correctly in my local environment. However, upon deploying it to Heroku, I encountered an error which is displayed below. All other APIs are fu ...

Vue3 - changes to array data not triggering automatic re-rendering

Being relatively new to Vue, I'm struggling to automatically update the array in my project. My webpage is simple - it consists of an input field and a button. When the button is clicked, the data is saved in a MongoDB database through my server. Be ...

Unable to locate the method within User.js

I'm encountering an issue with a method in express. I've included the error code below index.js app.post('/login', function (req, res) { User.findOne({ email: req.body.email }, function (err, user) { if (!user) { ...

How can I adjust a number using a shifter in JavaScript?

Searching for an event handler where I can use a shifter to adjust the value of a number by moving it left or right. Would appreciate any links to documentation on how to achieve this. Many thanks UPDATE Thanks to the suggestions from other users, I hav ...

Struggling to incorporate infinite scroll feature into JSON script that is already functioning smoothly

After developing a phonegap application, I created a page called photos.html to fetch photos from my server using JSON. However, despite successfully retrieving all the photos stored in my MySQL database on the server with JSON, I struggled to integrate In ...

I wonder about the origin of this variable

I found this example in a textbook. My confusion lies in the origin of this interval variable. Where does it come from? It's not defined within the data block, and you can't simply create a variable by assigning a value to it. Could it possibl ...

Increase the size of the button temporarily on a website

Hey there, I'm working on a clicker project and ran into an issue. When attempting to adjust the size of the button upon clicking, the animation isn't triggering. My goal is to change the size, not the width, of the button. Any guidance would be ...

Using Three.js to display multiple objects simultaneously causes my browser to crash

When it comes to rendering objects in a scene, I encountered an issue with loading multiple objects. Initially, loading all 3 objects as STL files worked fine. However, when I attempted to divide each object into multiple surfaces and create BufferGeometry ...