# 4.6 陣列排序(Sort)

在 `javascript/practice` 資料夾下，建立 `array_sort.html` 檔案，以便練習。

## Array.sort() 排序字串

預設上，sort() 排序的是字串。然後會影響原來的字串。

```javascript
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();

console.log(fruits); // ["Apple", "Banana", "Mango", "Orange"]
```

## Array.sort() 排序數值

如果陣列裡是數值，會發現排序出來的結果跟我們想的不一樣：

```javascript
var points = [40, 100, 1, 5, 25, 10];
points.sort(); // 字串方式去排序

console.log(points); // [1, 10, 100, 25, 40, 5]
```

### 關於 Compare Function(比較函式)

Compare Function 的用途是用來取代 sort() 函式預設的字串排序方式，也就是我們可以自訂排序方式，每次比較兩個數值，然後必需回傳負數、0、正數。

常見寫法：

```javascript
function(a, b){
  return a - b;
}
```

* 回傳如果是負數： 就先排 a 再排 b。
* 回傳如果是正數：就先排 b 再排 a。
* 回傳如果是 0：就不做任何更動。

### 例 1：排序由小到大

```javascript
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){
  return a - b;
});

console.log(points); // [1, 5, 10, 25, 40, 100]
```

解讀：

* 40、100 會被代入，a 是 40，b 是 100，兩者相減是負數，所以先排 40 再排 100。依此類推。

### 例 2：排序由大到小

只要將回傳的結果加上負號即可：

```javascript
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){
  return -(a - b);
});

console.log(points); // [100, 40, 25, 10, 5, 1]
```

解讀：

* 40、100 會被代入，a 是 40，b 是 100，兩者相減是負數，但因為加上了負號，所以回傳結果是正數，所以先排 100 再排 40。

## Array.reverse()

陣列整個反轉：

```javascript
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();       // 排序
fruits.reverse();    // 反轉

console.log(fruits); // ["Orange", "Mango", "Banana", "Apple"]
```

## 練習：排序物件陣列(Sorting Object Arrays)

請將以下的物件陣列，依照 year 來排序，由小到大：

```javascript
var cars = [
  {type:"Volvo", year:2016},
  {type:"Saab", year:2001},
  {type:"BMW", year:2010}
];

// 排序部份寫在這



console.log(cars);
```

參考作法：

{% embed url="<https://codepen.io/carlos411/pen/eYJoegg>" %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.webmix.cc/javascript/4.-javascript-chang-yong-nei-jian-han-shi/4.6-array-sort.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
