Reputation: 707
I have an array on Vue which contains 3 objects with name and rate, and a function that sorts by rate:
methods: {
sortByRate() {
this.complejos = this.complejos.sort(function(a, b) { return a.rate - b.rate });
}
}
What I need now is a function to sort by last added, that is, to order the items as they were.
Fiddle: https://jsfiddle.net/1u4mzqwj/
Upvotes: 1
Views: 450
Reputation: 913
You can add a Date (or Timestamp) to the object and sort it this way:
this.complejos = this.complejos.sort(function(a, b) { return a.addDate - b.addDate });
Upvotes: 0
Reputation: 12395
Either store the inital natural sorted array somewhere else or add a created timestamp and sort by that.
Something like that
methods: {
sortByRate() {
this.complejossorted = this.complejos.sort(function(a, b) { return a.rate - b.rate });
}
sortByNatural() {
this.complejossorted = this.complejos;
}
}
or add a created timestamp
Upvotes: 0
Reputation: 450
If the data is always added to the end of the array you could reverse the array:
sortByLastAdded() {
this.complejos = this.complejos.reverse()
}
See also: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse
Upvotes: 3