##### 标题：JavaScript排序

sort() 方法是最强大的数组方法之一.

## 排序数组

sort() 方法按照字母顺序对数组排序:

```var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();            // Sorts the elements of fruits
```

## 反转数组

reverse() 方法反转数组中的元素。.

```var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();            // Sorts the elements of fruits
fruits.reverse();         // Reverses the order of the elements
```

## 数字排序

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

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

## Compare 函数

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

```<button onclick="myFunction1()">Sort Alphabetically</button>
<button onclick="myFunction2()">Sort Numerically</button>

<p id="demo"></p>

<script>
var points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;

function myFunction1() {
points.sort();
document.getElementById("demo").innerHTML = points;
}
function myFunction2() {
points.sort(function(a, b){return a - b});
document.getElementById("demo").innerHTML = points;
}
</script>
```

## 随机排序数组

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

## 找到最高（或最低）值

```var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a});
// now points[0] contains the highest value
```

```var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});
// now points[0] contains the lowest value
```

## 对象数组排序

JavaScript数组通常包含对象:

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

```cars.sort(function(a, b){return a.year - b.year});
```

```cars.sort(function(a, b){
var x = a.type.toLowerCase();
var y = b.type.toLowerCase();
if (x < y) {return -1;}
if (x > y) {return 1;}
return 0;
});
```