Sorting multiple items with a watched value in Vue can be achieved by utilizing specific techniques and

I have set up a select element in my HTML code and I am looking to give users the option to sort a table based on the selected option values.

The information I need to organize (which consists of many objects) is shown below:

https://i.sstatic.net/d0p4Q.png

I am monitoring a select element that has a v-model value called "sort":

  watch: {
  search: function (val) {
    if (val.length === 0) return this.filtered = this.affiliates;

    this.filtered = this.affiliates.filter(function (cont) {
      return cont.shop_name.toLowerCase().indexOf(val.toLowerCase()) >= 0 || cont.app_name.toLowerCase().indexOf(val.toLowerCase()) >= 0;
    });
  },
  sort: function (val) {
    console.log(this.filtered);
  },

How can I arrange the objects based on the selected sorting value?

The data is stored in the variable this.filtered

I aim to sort by the following values:

 <select v-model="sort">
          <option value="date_installed">Latest</option>
          <option value="status">Status</option>
          <option value="share">Share</option>
        </select>

Answer №1

Although utilizing a watch can make it functional, it appears that using computed would be a more suitable approach.

The sort function requires a compare function to dynamically compare objects based on sorting preferences, which can be achieved by passing it as a key using bracket notation for accessor.

<template>
    <div>
        <select v-model="sortBy">
            <option value="date_installed">Latest</option>
            <option value="status">Status</option>
            <option value="share">Share</option>
        </select>
        <ul>
            <li v-for="item in filtered" :key="item.id">{{ item.app_name}}</li>
        </ul>
    </div>
</template>

<script>
export default {
    data() {
        return {
            sortBy: [],
            affiliates: [
                //...
            ]
        }
    },
    computed: {
        filtered() {
            if (val.length === 0) return this.affiliates;
            return this.affiliates.sort( (a,b) => {
                return a[this.sortBy] - b[this.sortBy]
            });
        }
    },
}
</script>

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

A guide on incorporating a JavaScript plugin using Vue.use() into a TypeScript project equipped with typings

Currently, I am facing an issue while attempting to integrate Semantic-UI-Vue into my Vue project. Upon trying to execute Vue.use(SuiVue), the following error message is displayed: Argument of type 'typeof import("semantic-ui-vue")' is not ass ...

Employing lodash for object comparison and removal from an array

In my current project, I am using lodash to compare two arrays of objects and extract the differences between them. The goal is to add this difference to the original data set while maintaining the existing data intact. For instance, if there are initially ...

Bootstrap's square-shaped columns

I would like to implement a grid of squares for navigation purposes. By squares, I mean that the colored areas should have equal width and height. Currently, I have achieved this using JavaScript, but I am interested in a CSS-only solution. My project is ...

Exploring the data types of dictionary elements in TypeScript

I have a model structured like this: class Model { from: number; values: { [id: string]: number }; originalValues: { [id: string]: number }; } After that, I initialize an array of models: I am trying to compare the values with the o ...

Preventing jQuery plugin from overriding default settings

I have created a jQuery plugin using the nested namespace pattern, inspired by the design template found in Addy Osmani's book. The plugin is a simple gallery and everything seems to be functioning correctly. However, I am facing an issue when attemp ...

Using onDoubleClick with MUI TextField: A Quick Guide

Whenever the user double clicks the input field, I would like to automatically select the text. I have created a function for this specific action: export const selectText = ( event: React.MouseEvent<HTMLInputElement | HTMLTextAreaElement, MouseEvent& ...

Encountering a 500 (Internal Server Error) while trying to insert data into the database through ajax

In the HTML code, I have a basic AJAX function that is triggered by a button press. The goal is to have the PHP script being called insert the JavaScript variable sent into a database. var myval = 'testuser'; // generated by PHP $.a ...

The spring submission function requires the use of two parameters

As a beginner in spring web applications, I am facing an issue where the request mapping receives a "dual" parameter when I submit a form. The form structure is as follows: <form action="" method="post" name="myform"> ...... </form> To submit ...

What steps should I take to resolve the 'Uncaught Error: Cannot find module 'path'' issue in my React.js application?

While developing a web application in react.js, I encountered errors that I couldn't solve despite trying various solutions found online. The console displays the following error: Error in Console: Uncaught Error: Cannot find module 'path' ...

Using pg-promise to insert a UUID into the database

I am in the process of setting up a new server and I want each customer to have a unique UUID identifier. My goal is to allow the customers name, parent company, and internal id to be input through a web interface, while the UUID is generated on the server ...

React: Modifying values of individual input fields

Utilizing React, I have developed a basic list that showcases data fetched from an API. The fetching and updating of data is done through axios. An issue arises when updating a specific element in the list, causing all inputs to clear except for the acti ...

Ensuring data is saved on multiple forms using ui-router in AngularJS

Implementation Details: I'm currently utilizing ui-router to load a form page in a ui-view div. I found an excellent example by Andres Ekdahi. My question is, how can I perform a $dirty check on multiple forms using the same directive? Form 1 < ...

Reasons why the success function is not functioning properly

Learning J-QUERY and JavaScript is a process that I'm fairly new to. My issue lies with adding checks and alert messages to my forms which submit data to an asp page and call a T-SQL procedure. Although the process works, I struggle with implementing ...

Creating a PDF document from HTML content using html2pdf in a Vue 3.js application: A step-by-step guide

I am currently exploring the possibility of converting my HTML content into a PDF format using the html2pdf library. So far, I have successfully achieved this with a simple one-file component where the HTML and a <button> within a <template> ta ...

What is the appropriate placement for setting Firebase auth state persistence in a Vue.js application?

Welcome Currently working on a web application using Quasar/Vue.js and Firebase that requires user authentication. My Objective I am aiming to implement a common feature - keeping users logged in even after they have closed the browser or tab. Potentia ...

Guide to effectively retrieving data from S3 and displaying a view at regular intervals of 4 seconds

In my current project, I am working on fetching a file from S3 and utilizing the data within that file to generate a map on a webpage. To achieve this task, I have set up an Express server along with the EJS templating engine for serving and rendering the ...

I'm having trouble getting my JQuery function to activate

I'm struggling to make my background image follow the movement of my mouse as it hovers over the objects with the #titleheader class. The page is displaying correctly, but the interactive functionality isn't working. I am developing in Django. I ...

What is the best way to link one element to another element?

Apologies for the mismatched title, but here's my issue: I need to create hidden checkboxes for each Polymer's paper-button div in jsp/style related problems. <%int i; %> <form ACTION="Computation.jsp"> <% for(i=0; i<n; ...

"Experiencing difficulties deploying Firebase functions - Encountering an error message stating 'Cannot read property 'firebase-admin' of

I'm currently facing an issue during the deployment of my Firebase functions and I am seeking assistance to resolve it. While the deployment itself appears to be successful, I keep encountering the following error: Cannot read property 'firebas ...

Component in Next Js fails to pass props when using getInitialProps

I am facing some challenges with Next Js and could really use some assistance. We have a component where I am utilizing "getInitialProps" to pass props to it during the server-side rendering process. However, no matter what I try, the props do not seem to ...