Search code examples
javascriptlodash

Toggle lodash orderBy ascending and descending


I have a method in my vue.js that is sorting my items by the date they registered in ascending but what I really wanted is for 1 unique button to be clicked and toggle between ascending and descending.

JS

sortAsc(customers) {
  // Click and sort registered customers by ascending
  let sort = _.orderBy(this.customers, 'registered', 'asc')
  this.sortedCustomers = sort
}

How can I make the above so when I click 1x sorts by ascending and click 2x sorts by descending?

Thanks


Solution

  • Add another property to the object (sortOrder) that saves the current sort order. Toggle it when you call the function - use asc if it's undefined or set to desc:

    sortAsc(customers) {
      this.sortOrder = this.sortOrder !== 'asc' ? 'asc' : 'desc'
    
      const sort = _.orderBy(this.customers, 'registered', this.sortOrder)
      this.sortedCustomers = sort
    }