# sort by multiple keys

{% tabs %}
{% tab title="💈範例" %}

```javascript
let votes = [
    { title: 'Apple', votes: 1 },
    { title: 'Milk', votes: 2 },
    { title: 'Carrot', votes: 3 },
    { title: 'Banana', votes: 2 }
];

// ⭐️ 一行搞定，真是天才❗️
let sorted = votes.sort((a,b) => 
    // 1. 先排 votes (多的人先)
    // 2. 再排 title (按字母順序)
    b.votes - a.votes || a.title.localeCompare(b.title)
);

/*
[
  { title: 'Carrot', votes: 3 },
  { title: 'Banana', votes: 2 },
  { title: 'Milk'  , votes: 2 },
  { title: 'Apple' , votes: 1 }
]
*/
```

{% endtab %}

{% tab title="🗣 討論" %}

* [How to sort an array of objects by multiple fields?](https://stackoverflow.com/questions/6913512/how-to-sort-an-array-of-objects-by-multiple-fields)
  {% endtab %}

{% tab title="⬇️ 應用" %}

* [class-average](https://lochiwei.gitbook.io/web/appendix/gas/projects/class-average "mention") - 排前三名時會用到。
  {% endtab %}
  {% endtabs %}
