7

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>

3 Answers 3

20

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))
  }
}
...
Sign up to request clarification or add additional context in comments.

2 Comments

Thanx, helped me as well.
I needed to add getDate() like new Date(a.date).getDate()
2

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.