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

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


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))  }}...


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


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 orderthis.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.