【问题标题】:How to sort array with 2 fields in Vue?如何在Vue中对具有2个字段的数组进行排序?
【发布时间】:2017-11-28 08:32:11
【问题描述】:

所以我有这张桌子:

我使用这个vue2 filter library,我只能使用它按单个字段排序。

我想做的是使用scoretime_consumed 字段按降序对数组进行排序。分数越高,time_consumed 越短,位置越高。

在上面的例子中,顺序应该是这样的;

1. 12 | 10141
2. 5 | 15233
3. 5 | 16233
4. 3 | 11495

我使用了库中的 orderBy 过滤器,但我只能使用

按分数排序
v-for="u in orderBy(users, 'score', -1)"

有没有更简单的方法来做到这一点?任何帮助将不胜感激。

【问题讨论】:

    标签: javascript arrays sorting vue.js computed-properties


    【解决方案1】:

    使用计算值对分数进行排序。

    console.clear()
    
    const scores = [
      {
        score: 3,
        time_consumed: 11495
      },
      {
        score: 5,
        time_consumed: 16233
      },
      {
        score: 5,
        time_consumed: 15233
      },
      {
        score: 12,
        time_consumed: 10141
      },
    ]
    
    new Vue({
      el:"#app",
      data:{
        scores
      },
      computed:{
        sortedScores(){
          const sorter = (a,b) => b.score - a.score || a.time_consumed - b.time_consumed
        
          return this.scores.sort(sorter)
        }
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
    <div id="app">
      <table>
        <tr v-for="score in sortedScores">
          <td>{{score.score}}</td>
          <td>{{score.time_consumed}}</td>
        </tr>
      </table>
    </div>

    排序器对这两个值都起作用,因为如果分数相等,它将最终使用 time_consumed。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-29
      • 1970-01-01
      • 1970-01-01
      • 2020-07-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多