NuzzeSicK
NuzzeSicK

Reputation: 707

Sort items by Last added Vue JS

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

Answers (3)

brandt.codes
brandt.codes

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

the full fiddle

Upvotes: 0

Daniel Kreiseder
Daniel Kreiseder

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

Eddy Vinck
Eddy Vinck

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

Related Questions