Guide to organizing a calculated attribute in vue.js

I'm struggling with organizing the already computed array of results.

Within Vue, I have successfully filtered images based on their ratio. Now, my goal is to sort these filtered results by date, name, or any other possible category.

Although I attempted to apply a sorting method to the array, I found that this solution doesn't update automatically and reflect the changes in real-time.

  data() {
    return {
      results: [],
      imgProperties: {
        imgId: [],
        imgRatio: [],
        imgCreateDate: []
      }
    };
  },
  computed: {
    resultsFiltered() {
      if (this.sliderVal == 0) {
        return this.results;
      } else {
        const obj = [];
        const arr = [];
        for (let i = 0; i < this.ratioIndeces.length; i++) {
          const element = this.ratioIndeces[i];
          obj.push(this.results[element]);
          arr.push(this.imgProperties.imgRatio[element]);
        }
        return obj;
      }
    }
  },

This current setup lacks any visible sorting solution.

I'm eager to learn where and how to implement sorting functionality.

The provided code snippet illustrates a portion of the existing structure, noting that ratios are calculated within the methods.

My objective is to arrange the array by imgCreateDate and imgRatio.

Answer №1

Sorting Example using imgRatio:

<p v-for="result in resultsFiltered | orderBy 'imgRatio'">{{ result.imgRatio }}</p>

or

<p v-for="result in resultsFiltered">{{ result.imgRatio }}</p>
computed: {
    resultsFiltered() {
      if (this.sliderVal == 0) {
        return this.results.sort((a, b) => { return b.imgRatio - a.imgRatio;});
      } else {
        const obj = [];
        const arr = [];
        for (let i = 0; i < this.ratioIndeces.length; i++) {
          const element = this.ratioIndeces[i];
          obj.push(this.results[element]);
          arr.push(this.imgProperties.imgRatio[element]);
        }

        return this.obj.sort((a, b) => { return b.imgRatio - a.imgRatio;});
      }
    }
  },

If you are using Vue3, refer to the migration guide here

Answer №2

If you need your computed property to utilize a data property for sorting purposes, you can achieve this with the following approach. Initially, I set up my data to contain both the original unsorted data and the current sort parameter:

  data: {
    origItems:[
      {name:'ray', age:10},
      {name:'apple', age:20},
      {name:'zula', age:9},
    ],
    sortType:''
  },

Next, I created my computed property to return values based on the sortType specified:

  computed:{
    items() {
      if(this.sortType === '') return this.origItems;
      if(this.sortType === 'name') {
        return this.origItems.sort((a,b) => {
          if(a.name < b.name) return -1;
          if(a.name > b.name) return 1;
          return 0;
        });
      }
      if(this.sortType === 'age') {
        return this.origItems.sort((a,b) => {
          if(a.age < b.age) return -1;
          if(a.age > b.age) return 1;
          return 0;
        });
      }
    }

This code could potentially be optimized further in terms of efficiency. For testing purposes, I structured it within the following layout:

<div id="app" v-cloak>
  <button @click="sort('name')">Sort by Name</button>
  <button @click="sort('age')">Sort by Age</button>
  <ul>
    <li v-for="item in items">{{ item.name}} - {{ item.age }}</li>
  </ul>
</div>

You can view a live demonstration of this implementation here: https://codepen.io/cfjedimaster/pen/eYYMVWr?editors=1011

Answer №3

Presented here is my most recent method for filtering and sorting results simultaneously based on specified parameters:

computed: {
  resultsFiltered () {
    return this.built.dataset.filter(img => {
      return this.customFilters.every(key => {
        const parameter = this.params[key]
        const args = parameter.map(val => this.customInputs[val]).slice(1)
        return filterMenus[key](img[parameter[0]], ...args)
      })
    }).sort(this.sortings[this.sortDirection][this.sortType])
  }
},

A breakdown of the individual components:

built.datatset - an array consisting of objects, where each img represents an object.

customFilters - an array containing different filter options such as 'ratio' or 'keyword', providing flexibility in filtering based on the available keys.

customInputs - captures user input data, whether it's a date range, ratio, keyword, year, etc.

sortings - involves comparing one image to another (img1 compared to img2).

sortDirection - determines the sorting direction as either ascending or descending, like 'img2.ratio - img1.ratio'.

sortType - specifies the sorting type as alphabetical, numerical, by date, or resetting to default view.

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

Double array summation function

It is necessary for me to calculate the total coursePrice from this JSON data source here using AngularJS (javascript). I need to calculate two sums: one for each school and another for all schools combined. I have already displayed all the data in a tabl ...

Retrieve the callback arguments using sinon.spy within a JavaScript promise

During my test with mocha and sinon, I encountered an issue where I couldn't retrieve a callback value from inside a promise scope of an HTTP-request due to the asynchronous nature of promises. It seems that by the time sinon.spy checks on the callbac ...

Struggling with eliminating the # from a URL in AngularJS

I am working on a single-page application built with AngularJS. The URL structure I currently have looks something like this: .../Angular/index.html. However, when I click on a link within the page, the URL transforms to .../Angular/index.html#/addStudent. ...

How is it possible that the whitelist in NestJs does not generate errors when using an incorrect

I am implementing a white list in my route's body validation to ensure that only data conforming to my model is accepted. If any parameter is sent that is not part of my model DTO, an error should be thrown. Here is my DTO: export class RegisterDTO ...

Exploring Vue.JS with Staggered Transitions and Enhancing User Experience with Loading More

The VueJS Guide offers a clever method for using the item's index to create a delayed transition for the items in the data set. You can learn more about it here. While this approach works great when the data set remains static, I'm encountering a ...

Electron does not prioritize the @css prefers-color-scheme option

I recently completed an Electron project and decided to incorporate dark mode support into it. However, for some reason, the dark mode feature is not functioning properly. Below you will find the dark.css styling that I have included in every page: @medi ...

Receiving HTTP POST data using Classic ASP script

I'm currently working on a project and have come across an area where I am facing some challenges. Despite my best efforts, I haven't been able to find a solution using Google. In my ASP web application, I've added an HTML canvas that I nee ...

Is it possible to utilize Sequelize model methods to articulate the given SQL query effectively?

I've been spending hours trying to convert the following SQL query into a Sequelize model method like findOne() - SELECT * FROM "Tariffs" WHERE "tariffType" = 'DateRange' AND (('${body.startDate}' BETWEEN "startDate" AND "endDate" ...

Using setInterval with Internet Explorer 10

In Internet Explorer 10, the setInterval function does not work properly. I have a web page where, upon form submission, a lengthy process is triggered on the server to download a file. To keep users updated on the progress, I utilize setInterval to repeat ...

Dynamically select checkbox groups based on items already listed in a textarea

Hello! Would you be able to review this example and provide guidance on how I can use jQuery to dynamically select the checkboxes that have the same text as in the textarea below? <br /> <br /> Default Items From Database <br /> < ...

Chrome can't locate VueJS locally

Recently, I encountered an issue where when trying to access http://localhost:8080/ in Chrome, I was redirected to a bad request page generated by the browser itself. However, if I accessed the network URL, for example, http://192.168.1.1:8080/, Chrome loa ...

Incorporating dynamic content changes for enhanced user experience can be achieved more effectively with AngularJS

I am utilizing a REST service to retrieve information for a banner. The goal is to dynamically update the slider on the main page using this data. Currently, I am using $http.get to fetch the data, and then implementing interpolation with additional ng-if ...

A solution for Array.includes to handle NaN values

While browsing some Javascript blogs, I stumbled upon the Array prototype methods .indexOf and .includes. I noticed that if an array includes NaN as a value, indexOf may not be able to detect it, leaving us with the option of using .includes. However, cons ...

The Vue composition api fails to update the text field's bound value

I've encountered an issue while trying to update an attribute of an object after initialization. Here's a simplified version of my component: <template lang="pug"> div v-text-field(v-model="object.name") v-text-field(v-model="ob ...

Increase and decrease a counter in Javascript by clicking on two separate image tags, with increments and decrements between 1 and 10

Hello! I really appreciate your help. I am currently facing the following issue: <div id="thumb1"> <img class="img-responsive" id="prova" src="img/thumb-up-dark.png" alt=""> <div id="pinline">0</div> ...

Using Jcrop and Pixastic for Image Cropping

Currently, I am in the process of creating a website focused on image manipulation. I have been utilizing a lot of functions in Pixastic, which have proven to be quite effective. However, I have been contemplating if there is room for improvement specifica ...

Looking to showcase the array list on the user interface

I'm attempting to use the map function in JavaScript to display a list, but I keep encountering an error that says "TypeError: Cannot read property 'map' of undefined". import React, { Component } from 'react' import constants fro ...

Switching from using a computed property in Vue 2 to implementing the Vue 3 Composition API

I am currently in the process of updating my Vue 2 application to Vue 3 and I have been exploring how to work with computed properties using the Composition API in Vue 3. One particular challenge I am facing is migrating a Vue 2 computed property that pro ...

Issue encountered: Failure to locate module 'socket.io' while attempting to execute a basic server JavaScript file

Below is my server.js file that I am attempting to run using node server.js: var app = require('express')(); var http = require('http').createServer(app); var io = require('socket-io')(http); //also tried socket.io instead of ...

The progress event of the XMLHttpRequest updates quickly, outpacing the speed of the upload itself

I've been working on setting up an upload form and using xhr to return the upload status to the user. Everything seems to be in place, but I'm facing a strange issue where the callbacks are happening too quickly and showing a higher percentage th ...