What methods can I use to sort content by its rating?

I am embarking on my inaugural project and attempting to construct a product filtering system. So far, I have successfully implemented search and category filters; however, configuring the rating filter has proven to be challenging.

Here is an excerpt of my code:

<div class="heading">
        <h6 class="mb-3">Filter By Area</h6>
      </div>
      <div class="form-check" v-for="filter in filters" :key="filter">
        <input class="form-check-input" type="radio" name="flexRadioDefault" id="flexRadioDefault1"
          @click="() => filterAccommodations(filter)">
        <label class="form-check-label area-filter-each" for="flexRadioDefault1">
          {{ filter }}
        </label>
      </div>

      <div class="heading">
        <h6 class="mb-3 mt-3">Filter By Rating</h6>
      </div>
      <div class="form-check" v-for="starRating in starRatings" :key="starRating">
        <input class="form-check-input" type="radio" name="flexRadioDefault" id="flexRadioDefault1"
          @click="() => starAccommodations(filter)">
        <label class="form-check-label area-filter-each" for="flexRadioDefault1">
          {{ starRating }} 
        </label>
      </div>

The area search function works perfectly without any issues, along with the functioning search bar.

In addition, here is the script section:

const filters = [
  "All",
  "Dagana",
  "Lhuentse",
  "Mongar",
  "Pemagatshel",
  "Tashiyangtse",
  "Trashigang",
  "Zhemgang",
];
const starRatings = [
  "All",
  "1",
  "2",
  "3",
  "4",
  "5",
];
export default {
  name: "SidebarFilter",
  props: ["filterAccommodations", "searchAccommodations" ,'filteredAccommodations','starAccommodations'],
  data() {
    return {
      filters,
      starRatings
    };
  },
};

The components I've developed for the search filter seamlessly integrate with another component in a parent file, which serves as a model for my reference.

Displayed below is the template of the Parent file:

<div class="container">
        <div class="row">
            <div class="col-md-3 col-lg-3 col-xl-3 col-sm-12 col-xs-12">
                <SidebarFilter :filterAccommodations="filterAccommodations"
                    :searchAccommodations="searchAccommodations" 
                    :starAccommodations="starAccommodations"
                />
            </div>
            <div class="col-md-9 col-lg-9 col-xl-9 col-sm-12 col-xs-12">
                <AccommodationElements :accommodations="accommodations" />
            </div>
        </div>
    </div>

I'm currently creating functions to execute queries on the JSON data. Here's an overview of my script:

import ACCOMMODATION_DATA from '../Accommodation_DATA.json'
methods: {
        filterAccommodations(filter) {
            this.resetAcccomodations();
            if (filter === "All") {
                this.accommodations = ACCOMMODATION_DATA;
            } else {
                this.accommodations = ACCOMMODATION_DATA.filter(accommodation => {
                    return accommodation.location_id.toLowerCase().includes(filter.toLowerCase());
                });
            }
        },

        starAccommodations(filter) {
            this.resetAcccomodations();
            if (filter === "All") {
                this.accommodations = ACCOMMODATION_DATA;
            } else {
                this.accommodations = ACCOMMODATION_DATA.filter(accommodation => {
                    return accommodation.star_rate.toLowerCase().includes(filter.toLowerCase());
                });
            }
        },
        searchAccommodations(search) {
            this.resetAcccomodations();
            this.accommodations = ACCOMMODATION_DATA.filter(accommodation => {
                return accommodation.title.toLowerCase().includes(search.toLowerCase());
            });
        },
        resetAccommodations() {
            this.accommodations = ACCOMMODATION_DATA;
        }
    }

Here is a snippet of the sample JSON file:

{
        "id": 100,
        "title": "Onofredo Walkden",
        "content": "Salivary operation NEC",
        "image_id": "http://dummyimage.com/512x517.png/cc0000/ffffff",
        "banner_image_id": "http://dummyimage.com/x.png/ff4444/ffffff",
        "location_id": "Tashiyangtse",
        "address": "9 Briar Crest Hill",
        "map_lat": 40.5845053,
        "map_lng": -8.0854006,
        "is_featured": true,
        "star_rate": 4,
        "date_created": "6/22/2021",
        "price": 19433.22
}

Answer №1

If you're looking to filter accommodations, you can try implementing it in the following way:

<template>
   <div>
      {{ filterAccommodations }}
   </div>
</template>




data() {
    return {
      title: "",
      location: "",
      starRate: 5,
    };
  },
  computed: {
    filterAccommodations() {
      return ACCOMMODATION_DATA.filter((acc) => {
        return (
          acc.location_id.toLowerCase().includes(this.location.toLowerCase()) &&
          acc.title.toLowerCase().includes(this.title.toLowerCase()) &&
          acc.star_rate === this.starRate
        );
      });
    },
  }

To set your filters, you will need input fields for title, location, and star rating.

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 visually appealing website designs with Firefox by implementing smooth background image transitions using Javascript with

Currently, I am facing an issue with the banner area on my website. The background of the banner is set to change every 10 seconds using JavaScript. However, there seems to be a flickering effect that occurs for a brief moment when the background-image is ...

Step-by-step guide on retrieving data from E-goi with REST API in Google Apps Script

Looking to extract data from the e-goi API, I found a .jar file in their documentation. Unfortunately, there are no examples provided for the REST API, leaving me unsure of how to access it directly. As I'm still new to programs like this, I could rea ...

Having trouble with NPM Moment.js in React: Why is moment__WEBPACK_IMPORTED_MODULE_2__format not functioning properly?

scenario, After resolving my current issue using dateFns (date-fns.org), I am interested in integrating Momentjs into the project as well. The task at hand involves converting data to a string format within an app built with create-react-app. However, wh ...

What is preventing the random images from appearing on my browser?

Having some trouble loading random images on a page using basic JavaScript code. Following homework instructions, but the images are not showing up in the web browser. Any assistance would be greatly appreciated. Here is the code: <?xml version="1.0" ...

The reason behind Node.js using 7 threads per process

Upon starting a Node.js process, the top command displays 7 threads connected to the process. What exactly are these threads responsible for? Furthermore, as the workload on the API rises and request handlers start asynchronously waiting for other upstre ...

Setting up an SSL certificate for an Express application: A step-by-step guide

I am currently trying to set up my Express server in order to pass the SSL certificate and transition from http to https. After going through the Express documentation, I still haven't been able to find a suitable solution. While some suggestions lik ...

The logical OR operator in JavaScript (denoted as ||)

Can anyone explain the functionality of this operator in JavaScript? I have come across this operator in two different contexts: //context 1 function(e){ e = e || window.event; //context 2 if(a || b) In C or C++, I understand that the return value of th ...

When dragging a new connection in jsPlumb, the existing one should be automatically removed

After using jsPlumb, I was able to create a setup with the following features: Multiple nodes functioning like nodes in a unique flowchart design. Each node has a single target where connections can be dropped. Every node has zero, one, or more exits. Ea ...

Learn the technique of swapping out a portion of a string with a value from an input field in real-time

My webpage has a form on the left side where users can input text, and on the right is some static text. I want the text on the right to update automatically as the user types in the input field on the left. In my HTML code, it looks something like this - ...

Identifying when several asynchronous JavaScript $.ajax requests have finished

I have a JavaScript function that runs a loop and makes asynchronous AJAX calls. I need to wait for all the AJAX calls to complete before updating the UI. Here is the loop: function sync_SyncLocalStorageToServer() { if (helper_IsAppOnline()) { ...

Instructions for creating a JavaScript click function that iterates through all records, not just the initial record

Although I'm new to web development and still learning the basics of html, javascript, etc., I have a problem that seems quite simple. The challenge lies in understanding javascript functions, which I find particularly tough to grasp. Here's what ...

Ensuring the presence of a bootstrap angular alert with protractor and cucumberJS

I am currently utilizing protractor, cucumberJS, and chai-as-promised for testing. There is a message (bootstrap alert of angularJS) that displays in the DOM when a specific button is clicked. This message disappears from the DOM after 6000 milliseconds. ...

remove item from list of objects

Currently, I am actively using vuejs 3 in conjunction with laravel. This is the object array that I am currently working with: [[Target]] : Array(3) 0: Proxy(Object) {id: '96', name: 'DESINCRUSTADOR DCALUXE - HIDROCAL ELECTRONICO', cat ...

Concealing the submit button until a file has been selected

How can I make the submit button invisible until a file is selected? <form action="upload.php" method="POST" enctype="multipart/form-data"> <input type="file" name="imageURL[]" id="imageURL" /> <input type="submit" value="submi ...

Having an issue with Jquery selector where the text does not match

HTML Code <select id="myDropdown"> <option selected="selected" value="0">default</option> <option value="1">bananas</option> <option value="2">pears</option> </select> Javascript Function setDr ...

Why is it that the window object in JavaScript lacks this key, while the console has it?

let myFunction = function declareFunc() { console.log(this); // window console.log(this.declareFunc); // undefined console.log(declareFunc); // function body } console.log(this) // window myFunction(); I understand that the this keyword in a functio ...

Angular - Switching Displayed Information

I am currently working with Angular 4 and I am attempting to switch between contenteditable="true" and contenteditable="false" Here is what I have so far: <h1 (dblclick)="edit($event)" contentEditable="true">Double-click Here to edit</h1> Al ...

Using a HTML tag within vue js

Is it possible to dynamically change a <p> tag inside my component to be an <h1> tag based on a prop? If so, how can this be achieved? <template> <p>Hello world</p> </template> ...

Attempting to showcase the text within an <a> element on a <canvas> element while ensuring there are no noticeable visual distinctions

Imagine having this snippet of code on a webpage: elit ac <a href="http://www.ducksanddos/bh.php" id='link'>Hello world!</a> nunc Now, picture wanting to replace the <a> tag with a <canvas> element that displays the same ...

Is there a way to incorporate an external JavaScript file into a .ts file without the need for conversion?

I have an external JavaScript file that I need to utilize in a .ts file without performing any conversion. Does anyone know how to use it within TypeScript without the need for conversion? ...