0

Greetings all and pardon my novice for I am just a mere beginner. I am trying to sort by ascending/ descending by using an @click and switch case. The method below however, does not sort at all. The very method works for every other data type other than the date (of course), which is why I am confused as this indicates yet another problem with the date data type specifically. I know date data types are very finnicky, so if any advice could be spared it would be greatly appreciated. Here is some supporting code for this problem. If anything else is needed please let me know.

 <th @click="sort('date')" scope="col">
            Date
            <div v-if="sortedKey == 'date'">
              <i v-if="sortAscending" class="fas fa-arrow-circle-up"></i>
              <i v-else class="fas fa-arrow-circle-down"></i>
            </div>
          </th>

export default {
  name: "ServiceTable",
  data() {
    return {
      pageCount: 10,
      query: "",
      localEntries: [],

      sortedKey: "",
      sortAscending: false,
    };
  },

computed: {
    computedList() {
      if (this.query.length == 0)
        return this.localEntries.slice(0, this.pageCount);
      let filteredList = this.localEntries
        .filter((element) => {
        .slice(0, this.pageCount);

      return filteredList;
    },
  },

sort(key) {
      this.sortAscending = !this.sortAscending;
      this.sortedKey = key;

      switch (key) {
      
      case "date":
          if (this.sortAscending)
            this.localEntries.sort((a, b) =>
              a.date > b.date ? 1 : -1
            );
          else
            this.localEntries.sort((a, b) =>
              a.date < b.date ? 1 : -1
            );
          break;
      }
sandrooco
  • 8,016
  • 9
  • 48
  • 86
  • 1
    Are your dates actual `Date` objects? If yes, you should be able to use `a.date.getTime() > b.date.getTime()` – sandrooco Jan 10 '22 at 15:47
  • Thank you very much that was useful and has showed the ascending/descending icon when clicked, when before it did not. This returned an error stating that getTime() is not a function. How does one declare this? Thank you for your time! –  Jan 10 '22 at 15:50
  • I think that your variable localEntries is a string or list of strings? Use the javascript date object to sort. (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) – Jacob Botha Jan 10 '22 at 15:53
  • The problem was that I needed to parse the date i.e. Date.parse(a.date). Thanks for the help guys. –  Jan 10 '22 at 17:27
  • If the values are *Date* objects, then use `(a, b) => a - b`(ascending) or `(a, b) => b - a` (descending). Using `a.date < b.date ? 1 : -1` treats the case of `a - b === 0` as false, which may lead to an unstable sort. See [*How to sort an array on dates with data using JavaScript?*](https://stackoverflow.com/questions/47070025/how-to-sort-an-array-on-dates-with-data-using-javascript) – RobG Jan 11 '22 at 01:36

0 Answers0