Sorting technique failing to reorganize list

I'm currently troubleshooting why my sorting function is not functioning as expected.

My goal is for it to operate similarly to this example: https://codepen.io/levit/pen/abmXgBR

The data I am working with is retrieved from an API:

<BookCard v-for='book in filteredBooks' :key='book.id' :book='book' />

While the search filter is functional, the sorting feature isn't. Here is a snippet of my data along with computed properties/methods:

  data() {
    return {
      books: [],
      order: 1, // Ascending
      search: '',
    };
  },

computed: {
    filteredBooks() {
      return this.filterBySearch((this.sortByRating(this.books)));
    },
  },

  methods: {
    filterBySearch(books) {
      return books.filter((book) => book.volumeInfo.title
        .toLowerCase().match(this.search.toLowerCase()));
    },

    sortByRating(books) {
      return books
        .sort((r1, r2) => (r2.volumeInfo.averageRating - r1.volumeInfo.averageRating)
        * this.order);
    },

    sort() {
      this.order *= -1;
    },
  },

To change the order, I have implemented a button:

<button v-bind:class="order === 1 ? 'descending' : 'ascending'" @click="sort">
  Reader Rating
</button>

If you have any suggestions or insights on what could be causing the issue, please share them as I am relatively new to Vue.

Thank you!

Answer №1

It's advisable not to pass the data property as an argument when it's already available inside the methods. Focus on sorting the filtered books instead of altering the original property, as the sort operation directly impacts it:

computed: {
    filteredBooks() {
      let filtered= this.filterBySearch().slice();
      return this.sortByRating(filtered)
    },
  },

  methods: {
    filterBySearch() {
      return this.books.filter((book) => book.volumeInfo.title
        .toLowerCase().match(this.search.toLowerCase()));
    },

   sortByRating(books) {
      return books.sort((r1, r2) => {
        if (
          typeof r2.volumeInfo.averageRating === "number" &&
          typeof r1.volumeInfo.averageRating === "number"
        ) {
          return (
            (r2.volumeInfo.averageRating - r1.volumeInfo.averageRating) *
            this.order
          );
        } else {
          return this.order * -1;
        }
      });
    },

    sort() {
      this.order *= -1;
    },
  },

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 Adding Items to React To-Do List

As I work on creating a React todo app following a tutorial, I have encountered an issue. Despite having components and context files set up, the addItem function does not render the item and date into the todo list when the 'Add todo' button is ...

Is there a way to set it up so that my section remains hidden until the submit button is pressed, rather than disappearing every time I input a single character?

How can I modify the behavior in vue.js so that a certain section is hidden only after the user clicks on the submit button? Currently, the section disappears every time a single letter is entered. I want the visibility toggling with V-if and V-else to o ...

Updating an array of objects within an array using another array of objects

There are two JavaScript Arrays: let x = [ { id: 'Abc', children: [ { id: 12, name: 'john' }, { id: 13, name: 'dow' ...

Leverage VueJS and VueX to seamlessly integrate firebase 9 functions within my application

I am currently in the process of developing a blog application using Firebase version 9, VueJs version 3, and VueX. All functionalities such as user registration and authentication are working smoothly. However, I encountered an error when attempting to a ...

Find and delete an item from a JSON array

Currently, I am attempting to locate a specific object within a JSON array and remove it. The structure of my JSON array containing objects is as follows: var data = [{ {id: "1", name: "Snatch", type: "crime"}, {id: "2", name: "Witches of Eastwic ...

Express.js POST Request Not Being Accepted | 404 Error Detected

I am encountering difficulties implementing PayPal on my website. Whenever I attempt a post request, including using Postman, I receive a standard 404 error page instead of the expected response. The console shows no errors, leading me to believe that the ...

What is the best way to exclude an external HTML file from being displayed on the home page?

shopping_cart.php <div id="main-container"> <div class="container"> <span class="top-label"> <span class="label-txt">Shopping Cart</span> </span> <div class="content-area"> <div class="con ...

Utilizing JavaScript to create multiple HTML tables from JSON data

Is it necessary to create separate tables in HTML for each set of JSON data when all tables have the same number of columns (2 columns)? I am looking to minimize the JavaScript function that displays the table with the current JSON data. Can I use one tabl ...

What is the best way to incorporate a massive HTML string into a WebView using the LoadHTMLString technique?

I am struggling to display an HTML string on a UIWebView using the 'LoadHTMLString' method. Below is the code snippet I am using: [wv loadHTMLString:[NSString stringWithFormat:@"<!DOCTYPE html><html><head><meta name=\" ...

Can the ajaxsetup error handler be used with the POST method?

I have a strange question - does the global error handler applied when using ajaxsetup get triggered in case of an Ajax error on a POST request? I've tried handling Ajax errors in several places, but the error handler is only being hit for GET reques ...

Next.js allows for passing dynamically loaded server-side data to all components for easy access

(I've recently started working with Next.js and inherited a project built using it, so please forgive me if this is something obvious that I'm missing) I have a set of data that needs to be loaded server-side on each request. Initially, I had im ...

The primary origin of TypeScript is derived from the compiled JavaScript and its corresponding source map

Being new to sourcemaps and typescript, I am faced with a project that has been compiled into a single javascript file from multiple typescript files. The files available to me are: lib.js (the compiled js code of the project) lib.js.map (the source map ...

Determine whether the Bootstrap data-style attribute is enabled or disabled

I have a bootstrap checkbox that I would like to trigger an alert dialog when it is switched off. <div class="row"> <link href="css/bootstrap-toggle.min.css" rel="stylesheet"> <script src="javascript/bootstrap-toggle.min.js ...

Transmit a base64-encoded image in an HTTP request to the server

I am currently working on sending a base64 image using the request npm module from a nodejs/express application to another REST API endpoint. Below is the code I am using: First, I have middleware set up using multer and datauri to upload the image in mem ...

What is the mechanism by which a Node.js server handles incoming requests?

Suppose I am working with this code snippet. I am using ExpressJS, although the server part doesn't seem much different from vanilla Node.js. var express=require('express'); var settings=JSON.parse(fs.readFileSync('settings.json' ...

Conceal component while navigating in VueJs

I am working on a Vue project. I am trying to implement a feature where a component is hidden while the user scrolls, but then reappears once the scrolling stops. I have tried using a scroll event, but the component does not show up again. <div c ...

Data exchange among sibling form components

I have a two-step form that is divided into switchable tabs. It is crucial for the user to seamlessly move from one tab to another without losing any information that has already been filled out. Therefore, I am looking for a solution to prevent React from ...

React JS Bootstrap Dropdown Troubleshooting

I'm facing a challenge in my React.js project while trying to implement a filter. The issue is that the list appears when I click on the button, but it doesn't disappear on the second click or if I click outside the list. Initially, I imported t ...

Selecting the optimal data structure: weighing the benefits of using boolean check versus array .include (balancing performance and redundancy

My objects can have one or more properties assigned, with a total of 5 different properties in my case. To illustrate this, let's use a simple movie example where each movie can be assigned from 5 different genres. I have come up with two methods to ...

How can I display hardcoded array information as comments along with responses?

Currently, I am facing a challenge in displaying my hardcoded array data as comments with replies. The requirement is to achieve this within a single component file. While I have successfully managed to print the data out as a list, the desired outcome sh ...