6

Is there a function or way to sort an array by date or formatted date?

var sortbydate = new Vue({
  el: '#sortbydate',
  data: {    
    items: [
      { codeName: 'Looper', date: '25.03.1980' },
      { codeName: 'Sweetze', date: '25.03.1981' },
      { codeName: 'Lycon', date: '01.08.1991' }
    ]
  }
})
<ul id="sortbydate">
  <li v-for="(item, index) in items" style="list-style:none">
    {{ index }} - {{ item.codeName }}
  </li>
</ul>
radeveloper
  • 716
  • 2
  • 9
  • 18

3 Answers3

17

Just had to do this so I'll write down the simplest solution:

...
computed: {
    sortedItems: function() {
        this.items.sort( ( a, b) => {
            return new Date(a.date) - new Date(b.date);
        });
        return this.items;
    }
}
...

Or if you want to a one liner

...
computed: {
  sortedItems: function() {
    return this.items.sort((a, b) => new Date(a.date) - new Date(b.date))
  }
}
...
peaceman
  • 1,483
  • 8
  • 18
1

One solution can be:

  1. Add unformatted date as helper field.
  2. Use momentJS to create moment object from your formatted date.
  3. Sort it e.g. based on those answers: Sort Javascript Object Array By Date
Community
  • 1
  • 1
Marek Urbanowicz
  • 9,057
  • 7
  • 48
  • 74
1

Normally, you would require something like:

/** ...somewhere inside a method of your component
* but it is always better to keep such functions in a services folder
* you could not only need it elsewhere, but at the same time, it maintains the purpose 
* of your component too. */

// assuming you want it in ascending order
this.items.sort((a, b) => {
  if (Date.parse(a.date) > Date.parse(b.date)) {
     return 1
  } else if (Date.parse(a.date) < Date.parse(b.date)) {
     return -1
  } else {
     return 0
  }
})

But this won't work in your case as your format is not as per the Date.parse spec which will link you to the date-time ISO 8601 formats here

quick note:

new Date('25.03.1980') // Invalid Date (Throws an error if your date is incorrect)
Date.parse('25.03.1980') // NaN, using (Date.parse will not throw error!)

So, if possible you would need to change your format, or else use a library, I recommend momentjs.

Amresh Venugopal
  • 8,159
  • 4
  • 33
  • 48