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>
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.
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.
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))
}
}
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With