Creating a sorting function in VueJS requires a few key steps

I'm working on implementing a sorting function in my VueJS code that includes the following options: Price: Low to High, Price: High to Low.

Here is my template:

<div name="divSortBy">
        <span>
          Sort by:
        </span>
        <select v-model="sort" name="selectSortBy">
          <option
            v-for="item in sortedList"
            :key="item.id"
            name="selectOptionsSortBy"
            :value="item"
            @click="sortBy"
            v-text="item.title"
          ></option>
        </select>
      </div>

This is inside data() { return {} }:

sortByItems: [
    {
      id: 1,
      title: 'Price: Low to High',
      sort: 1
    },
    {
      id: 2,
      title: 'Price: High to Low',
      sort: 2
    }
  ],
  sort: null
productsList: [],

And here is the computed section:

computed: {
sortedList() {
  // FILTER HERE
  if (this.sort) {
    if (this.sort.id === '1') {
      console.log(this.sort.title) // console log for testing purposes
      this.productsList.sort(function(a, b) {
        return a.price - b.price
      })
    } else if (this.sort.id === '2') {
      console.log(this.sort.title)
    }
  }

  return this.sortByItems
}

Although I attempted to use the following sorting function, it doesn't seem to be working as expected:

this.productsList.sort(function(a, b) {
        return a.price - b.price
      }

Just to clarify, productsList: [] contains a list of objects and I need to sort them based on the price field before displaying them on the page.

Thank you!

Answer №1

To customize the sorting algorithm, you can pass a comparator function

Check out the DEMO

if (this.sort.id === "1") {
  return [...this.productsList].sort(function (a, b) {
    return a.price - b.price;
  });
} else if (this.sort.id === "2") {
   return [...this.productsList].sort(function (a, b) {
    return b.price - a.price;
  });
}

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

Obtain the total number of result entries

I'm working on a project involving JS and PHP. My goal is to call a PHP file using Ajax and have it return the count of result lines. I use echo for this: $connection = new PDO($source, $user); $query = "SELECT * FROM scores WHERE username = '" ...

Tips for retrieving the posted object in angularJS

My current challenge involves creating an object with a defined name, posting it into a database, and then immediately finding its position and obtaining its id. However, I have noticed that using "get" right after "post" retrieves the data before it' ...

Certain browsers have difficulty running CSS keyframes animations

As I work on my website, I have integrated a CSS keyframes animation that is triggered by clicking a link connected to a JavaScript function. Here is an excerpt from my CSS file: #banner { background-color: #00BBD2; position: absolute; width: 100%; heigh ...

Experiencing issues with this.$refs returning undefined within a Nuxt project when attempting to retrieve the height of a div element

I am struggling with setting the same height for a div containing Component2 as another div (modelDiv) containing Component1. <template> <div> <div v-if="showMe"> <div ref="modelDiv"> <Comp ...

Issue with handling .bind in Angular's karma/jasmine tests Angular's karma/j

When writing unit tests for my functions, I encountered an issue with a bound function in the test runner. The problem arose when trying to bind a function to have reference to 'this' inside an inner function. Here is the code snippet in question ...

"Encountering an issue with the Foreach function in nextjs when iterating through

I attempted to iterate through each character in a String, but the SPANS are not displaying. What could I be doing incorrectly? export default function Work() { const logoText = "The future starts here."; return ( <div className=& ...

How can I make the fullcalendar 'moreLink' popover stay open when clicking outside?

Currently, I am working with FullCalendar v6 on nextjs. One built-in feature that caught my attention is the event popover that appears when there are too many events, accessible by clicking "more." However, I am facing a challenge in preventing this pop ...

Managing Numerous Ajax Calls

Dealing with Multiple Ajax Requests I have implemented several Like Buttons on a single PHP Page, which trigger the same Ajax function when clicked to update the corresponding text from Like to Unlike. The current code works well for individual Like Butt ...

Choosing the relevant kendo row on two different pages

I am facing a situation where I have a Kendo grid displayed on a dashboard page. Whenever a user selects a row in this grid, I need to load the same row in another Kendo grid on a separate ticket page to showcase the details of that particular ticket. The ...

Is there an appropriate method in Vue/Nuxt for managing and altering component data without using lifecycle hooks?

Scenario: I am dealing with a component that showcases a datatable listing Applications. Upon clicking a row, it triggers the opening of another component with appropriately loaded fields (for new or edit). The Challenge: The component loads a reference t ...

Problem with displaying images and videos in a lightbox gallery

Currently, I am encountering an issue with the lightbox feature on my website. When trying to play a video, there seems to be a layer (div tag) blocking it, preventing me from playing or stopping the video. This problem occurs when clicking on an image fir ...

The jQuery mouseout functionality seems to be malfunctioning and not responding as expected

I am currently developing a slider that displays details when the mouse hovers over the logo, and hides the details when the mouse moves away from the parent div. jQuery('.st_inner img').mouseover(function() { jQuery(this).parent().siblings( ...

Truncating long text labels in Material UI Autocomplete using ReactJS

I am currently utilizing the material UI autocomplete feature and I have a specific requirement to trim the label when it is too lengthy. <Autocomplete id="combo-box-demo" options={top100Films} getOptionLabel={(option) =& ...

Leveraging JavaScript to extract data from a dropdown menu and apply it to a different section

I am working on a project that involves an HTML section where a user can choose a billing term from a drop-down list. I am in the process of writing JavaScript code to capture the selected option value and use it in another part of the webpage. Here is a ...

Transform a delimited string and an array of objects into a new format

Is there a way to easily convert a delimited string into an array of objects with data binding functionality? ng-list is suitable for arrays of strings. However, I have an array of objects where I want to delimit the text property for easy editing. Works ...

Storing user credentials in Firestore after registration - best practices

Hi, I need some assistance with storing user credentials in Firestore after they sign up. Unfortunately, I keep encountering the following error: Invalid collection reference. Collection references must have an odd number of segments, but userDatabase/QMJ ...

Make sure that a specific script is loaded prior to another script

I'm struggling to understand how scripts are loaded on a page. I have jQuery plugins that rely on other scripts. Specifically, I am using the timeago jQuery plugin. I have loaded these scripts in the head in the following order: <script src="< ...

Adding a fresh HTML element to a list at a designated location

I found this excellent example on CODEPEN Is there a way to insert a new random number into the list so that it appears after 24 but before 19? Is there an efficient solution or do I need to manually check each li element and determine where to place the ...

Error loading 'protobuf.js' while retrieving Firestore document

When trying to run a basic node file with Firebase and Firestore, the following code was used: const firebase = require("firebase"); const http = require('http') require("firebase/firestore"); firebase.initializeApp({ apiKey: '...' ...

What is the alternative to using toPromise() when utilizing await with an Observable?

This website mentions that "toPromise is now deprecated! (RxJS 5.5+)", however, I have been utilizing it recently with AngularFire2 (specifically when only one result is needed) in the following manner: const bar = await this.afs.doc(`documentPath`).value ...