0

I'm doing a list of items by using a v-for and for each properties i'm trying to sort them by ascending and descending.

The fact is I trigger the sort function on a v-btn to sort by ascending but when i click again nothing happen. I would like to reverse the sort and etc. when I click again on it.

My current method for on of my property is :

sortByScope()
      {
        this.alerts.sort(function(a, b){
            if(a.scope < b.scope){ return -1 }
            if(a.scope > b.scope){ return 1 }
            return 0
        })
      },

Do you have any ideas ?

Thanks for your attention

2
  • 2
    you mean like this solutione? stackoverflow.com/a/50503194/4173464 Commented Feb 19, 2020 at 9:23
  • wow ! I thought i searched in all Stack topics but you nailed it ! Thank you ! Commented Feb 19, 2020 at 9:45

1 Answer 1

1

If I understand your question correctly, you want your button to sort ascending or descending based on the current sorting of the column. You can do so by using a toggle flag:

sortByScope() {
  this.alerts.sort(function (a, b) {
    return this.sortScopeToggle
      ? a - b
      : b - a;
  });
  this.sortScopeToggle = !this.sortScopeToggle;
}

Where sortScopeToggle is a boolean that keeps track of the sorting order, and based on this boolean, a ternary operation returns the sorting algorithm.

Sign up to request clarification or add additional context in comments.

3 Comments

Why not only one handler and within the handler use the ternary condition?
this.alerts.sort((a, b) => this.sortScopeToggle ? (a - b) : (b - a));
I have several properties to sort and @db1975 redirect me to an other topic with is exactly what i needed link. With one method and with using a computed one it work like a charm.

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.