Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an array by date using Vue.js 2

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>
like image 739
radeveloper Avatar asked Feb 14 '17 11:02

radeveloper


People also ask

How do you sort dates in an array?

To sort an array of objects by date property: Call the sort() method on the array. Subtract the date in the second object from the date in the first. Return the result.

How do I sort a date in TypeScript?

To sort an array of objects by date in TypeScript: Call the sort() method on the array, passing it a function. The function will be called with 2 objects from the array. Subtract the timestamp of the date in the second object from the timestamp of the date in the first.


1 Answers

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))
  }
}
...
like image 173
peaceman Avatar answered Sep 19 '22 10:09

peaceman