Search code examples
javascriptarrayssortingvue.jscomputed-properties

How to sort array with 2 fields in Vue?


So I have this table:

enter image description here

And I use this vue2 filter library and I can only sort by a single field using that.

What I wanted to do is to sort the array in descending order using the score and time_consumed field. The higher the score and shorter the time_consumed, the higher the place.

In the example above, the order should look like;

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

I used the orderBy filter from the library but I can only sort by score using

v-for="u in orderBy(users, 'score', -1)"

Is there a simpler way to do this? Any help would be much appreciated.


Solution

  • Use a computed value to sort your scores.

    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>

    The sorter works on both values because if the scores are equal, it will end up using the time_consumed.