Reputation: 946
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>
Upvotes: 7
Views: 31210
Reputation: 1721
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))
}
}
...
Upvotes: 20
Reputation: 9549
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.
Upvotes: 2
Reputation: 13674
One solution can be:
Upvotes: 1