Greg Fielding
Greg Fielding

Reputation: 557

Vue.js how to sort filtered results by date

We are launching an events application where users can search upcoming music festivals. We also want the filtered search results to display in chronological order by "startDate".

Our event cards:

<v-card flat class="pa-2 mb-3 eventcard" v-for="event in filteredEvents" :key="event.id"></v-card>

Then our computed property:

filteredEvents: function(){
    return this.$store.getters.loadedEvents.filter((event) => {
      return event.title.toLowerCase().match(this.search.toLowerCase())
    })
  }

And finally, an example of an event start date:

startDate:"2018-04-13"

Per the docs, I've tried adding "_.orderBy(this.event, 'startDate')" but I just get the error this.search.toLowerCase(...).orderBy is not a function

Any ideas? Thanks!

Upvotes: 1

Views: 5241

Answers (1)

Jacob Goh
Jacob Goh

Reputation: 20845

use .sort

export default {
  filteredEvents: function() {
    return this.$store.getters.loadedEvents
      .filter(event => {
        return event.title.toLowerCase().match(this.search.toLowerCase());
      })
      .sort(function(a, b) {
        // Turn your strings into dates, and then subtract them
        // to get a value that is either negative, positive, or zero.
        return new Date(b.startDate) - new Date(a.startDate);
      });
  }
};

method from https://stackoverflow.com/a/10124053/5599288

Upvotes: 2

Related Questions