Home > OS >  Why my sorting array script not working in Vue.js?
Why my sorting array script not working in Vue.js?

Time:08-16

Well, I have a problem with sorting this table by Date. The sort function as a determinant of what sort we should use - works, but the sort function doesn't work anymore and I don't know why.

html:

<th @click = "sort('data_produktu')" >Data</th>

data:

messages: [],
   currentSort:'data_produktu',
     currentSortDir:'asc',

methods:

sort: function(s){
        
      if(s === this.currentSort) {
        this.currentSortDir = this.currentSortDir==='asc'?'desc':'asc';
      }
      this.currentSort = s;
      console.log(this.messages);
    }

computed:

sortedMessages:function() {
      return this.messages.sort((a,b) => {
        let modifier = 1;
        if(this.currentSortDir === 'desc') modifier = -1;
        if(a[this.currentSort] < b[this.currentSort]) return -1 * modifier;
        if(a[this.currentSort] > b[this.currentSort]) return 1 * modifier;
        return 0;
      });
    }

Array(console.log output because Im fetching it from DB):

0: {id_komunikat: '4', data_produktu: '2022-08-12 20:05:30', tresc: 'Example info', typ: '2', status_komunikatu: '1', …}
1: {id_komunikat: '5', data_produktu: '2022-08-12 20:05:36', tresc: 'Example info', typ: '2', status_komunikatu: '1', …}
2: {id_komunikat: '6', data_produktu: '2022-08-12 20:05:39', tresc: 'Example info', typ: '2', status_komunikatu: '1', …}
3: {id_komunikat: '7', data_produktu: '2022-08-12 20:05:47', tresc: 'Example info', typ: '1', status_komunikatu: '1', …}

CodePudding user response:

I see that data_produktu is a date, sorting date can't be sorted, with bigger than > or less than <, but by subtraction timestamps.

Ex:

array.sort(function(a,b){
  return new Date(b) - new Date(a);
});

CodePudding user response:

The computed function looks suspicious to me. It probably would cause infinite loop, because you also mutate this.messages in-place by invoking .sort() method. I suggest change it to:

sortedMessages:function() {
  //       use `.slice()` to clone first
  this.messages.slice().sort((a, b) => ...)
  • Related