Search code examples
javascriptvue.jssortingvuejs2computed-properties

How to sort a computed property in vue.js


I don't know how to sort an already computed array of results.

In Vue, I filter images by their ratio. Now I want to sort the individual results by date, name or whatever is possible.

I tried sorting the array with a method, but this solution does not automatically recalculate and dynamically display the sorted results.

  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;
      }
    }
  },

There is no sort approach to be seen here.

I would like to know how or where to start.

The code example shows an excerpt of the current structure. The ratio is calculated in the methods.

I would like to sort the array by imgCreateDate and imgRatio.


Solution

  • here is my latest approach to filter the results and sort them by parameters at the same time:

    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])
      }
    },
    

    the single elements:

    built.datatset = is an array of objects. Each img is an object.

    customFilters = is an array with filter options. like 'ratio' or 'keyword'. So I can filter with every key I got in the list.

    customInputs = whatever the user types in. A date range, a ratio, a keyword, a year, ...

    sortings = compare img1 to img2

    sortDirection = up or down. like 'img2.ratio - img1.ratio'

    sortType = alphabetical, numerical, by date or reset to default view