【问题标题】:How to reverse sort again after sort an array of objects?排序对象数组后如何再次反向排序?
【发布时间】:2020-02-19 09:17:30
【问题描述】:

我正在使用 v-for 做一个项目列表,并且对于每个属性,我试图通过升序和降序对它们进行排序。

事实是我触发了 v-btn 上的排序功能以按升序进行排序,但是当我再次单击时没有任何反应。当我再次点击它时,我想反转排序等等。

我目前对我的财产的处理方法是:

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

你有什么想法吗?

感谢您的关注

【问题讨论】:

标签: javascript arrays sorting vue.js


【解决方案1】:

如果我正确理解您的问题,您希望您的按钮根据列的当前排序进行升序或降序排序。您可以通过使用切换标志来做到这一点:

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

其中sortScopeToggle 是一个跟踪排序顺序的布尔值,基于此布尔值,ternary operation 返回排序算法。

【讨论】:

  • 为什么不只有一个处理程序和处理程序内使用三元条件?
  • this.alerts.sort((a, b) =&gt; this.sortScopeToggle ? (a - b) : (b - a));
  • 我有几个属性要排序,@db1975 将我重定向到另一个主题,这正是我需要的 link。使用一种方法并使用计算方法,它就像一个魅力。
猜你喜欢
  • 2014-05-15
  • 1970-01-01
  • 2023-02-21
  • 1970-01-01
  • 2023-04-09
  • 2017-02-19
  • 2013-12-10
  • 2020-06-07
  • 2017-02-21
相关资源
最近更新 更多