sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

The time and space complexity of the sort cannot be guaranteed as it depends on the implementation.

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

句法

arr.sort([compareFunction])
					

参数

compareFunction 可选
Specifies a function that defines the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value.
firstEl

The first element for comparison.

secondEl

The second element for comparison.

返回值

The sorted array. Note that the array is sorted in place , and no copy is made.

描述

compareFunction is not supplied, all non- undefined array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order. For example, "banana" comes before "cherry". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in the Unicode order. All undefined elements are sorted to the end of the array.

Note : In UTF-16, Unicode characters above \uFFFF are encoded as two surrogate code units, of the range \uD800 - \uDFFF . The value of each code unit is taken separately into account for the comparison. Thus the character formed by the surrogate pair \uD655\uDE55 will be sorted before the character \uFF3A .

compareFunction is supplied, all non- undefined array elements are sorted according to the return value of the compare function (all undefined elements are sorted to the end of the array, with no call to compareFunction )。若 a and b are two elements being compared, then:

  • compareFunction(a, b) returns less than 0, sort a to an index lower than b (i.e. a comes first).
  • compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behavior, thus, not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
  • compareFunction(a, b) returns greater than 0, sort b to an index lower than a (i.e. b comes first).
  • compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned, then the sort order is undefined.

So, the compare function has the following form:

function compare(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}
						

To compare numbers instead of strings, the compare function can simply subtract b from a . The following function will sort the array in ascending order (if it doesn't contain Infinity and NaN ):

function compareNumbers(a, b) {
  return a - b;
}
						

sort method can be conveniently used with function expressions :

var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
  return a - b;
});
console.log(numbers);
// [1, 2, 3, 4, 5]
						

ES2015 provides arrow function expressions with even shorter syntax.

let numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => a - b);
console.log(numbers);
// [1, 2, 3, 4, 5]
						

Objects can be sorted, given the value of one of their properties.

var items = [
  { name: 'Edward', value: 21 },
  { name: 'Sharpe', value: 37 },
  { name: 'And', value: 45 },
  { name: 'The', value: -12 },
  { name: 'Magnetic', value: 13 },
  { name: 'Zeros', value: 37 }
];
// sort by value
items.sort(function (a, b) {
  return a.value - b.value;
});
// sort by name
items.sort(function(a, b) {
  var nameA = a.name.toUpperCase(); // ignore upper and lowercase
  var nameB = b.name.toUpperCase(); // ignore upper and lowercase
  if (nameA < nameB) {
    return -1;
  }
  if (nameA > nameB) {
    return 1;
  }
  // names must be equal
  return 0;
});
						

范例

Creating, displaying, and sorting an array

The following example creates four arrays and displays the original array, then the sorted arrays. The numeric arrays are sorted without a compare function, then sorted using one.

var stringArray = ['Blue', 'Humpback', 'Beluga'];
var numericStringArray = ['80', '9', '700'];
var numberArray = [40, 1, 5, 200];
var mixedNumericArray = ['80', '9', '700', 40, 1, 5, 200];
function compareNumbers(a, b) {
  return a - b;
}
console.log('stringArray:', stringArray.join());
console.log('Sorted:', stringArray.sort());
console.log('numberArray:', numberArray.join());
console.log('Sorted without a compare function:', numberArray.sort());
console.log('Sorted with compareNumbers:', numberArray.sort(compareNumbers));
console.log('numericStringArray:', numericStringArray.join());
console.log('Sorted without a compare function:', numericStringArray.sort());
console.log('Sorted with compareNumbers:', numericStringArray.sort(compareNumbers));
console.log('mixedNumericArray:', mixedNumericArray.join());
console.log('Sorted without a compare function:', mixedNumericArray.sort());
console.log('Sorted with compareNumbers:', mixedNumericArray.sort(compareNumbers));
						

This example produces the following output. As the output shows, when a compare function is used, numbers sort correctly whether they are numbers or numeric strings.

stringArray: Blue,Humpback,Beluga
Sorted: Beluga,Blue,Humpback
numberArray: 40,1,5,200
Sorted without a compare function: 1,200,40,5
Sorted with compareNumbers: 1,5,40,200
numericStringArray: 80,9,700
Sorted without a compare function: 700,80,9
Sorted with compareNumbers: 9,80,700
mixedNumericArray: 80,9,700,40,1,5,200
Sorted without a compare function: 1,200,40,5,700,80,9
Sorted with compareNumbers: 1,5,9,40,80,200,700
						

Sorting non-ASCII characters

For sorting strings with non-ASCII characters, i.e. strings with accented characters (e, é, è, a, ä, etc.), strings from languages other than English, use String.localeCompare . This function can compare those characters so they appear in the right order.

var items = ['réservé', 'premier', 'communiqué', 'café', 'adieu', 'éclair'];
items.sort(function (a, b) {
  return a.localeCompare(b);
});
// items is ['adieu', 'café', 'communiqué', 'éclair', 'premier', 'réservé']
						

Sorting with map

compareFunction can be invoked multiple times per element within the array. Depending on the compareFunction 's nature, this may yield a high overhead. The more work a compareFunction does and the more elements there are to sort, it may be more efficient to use map for sorting. The idea is to traverse the array once to extract the actual values used for sorting into a temporary array, sort the temporary array, and then traverse the temporary array to achieve the right order.

// the array to be sorted
var list = ['Delta', 'alpha', 'CHARLIE', 'bravo'];
// temporary array holds objects with position and sort-value
var mapped = list.map(function(el, i) {
  return { index: i, value: el.toLowerCase() };
})
// sorting the mapped array containing the reduced values
mapped.sort(function(a, b) {
  if (a.value > b.value) {
    return 1;
  }
  if (a.value < b.value) {
    return -1;
  }
  return 0;
});
// container for the resulting order
var result = mapped.map(function(el){
  return list[el.index];
});
						

There is an open source library available called mapsort which applies this approach.

规范

规范
ECMAScript (ECMA-262)
The definition of 'Array.prototype.sort' in that specification.

浏览器兼容性

The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
sort Chrome 1 Edge 12 Firefox 1 IE 5.5 Opera 4 Safari 1 WebView Android 1 Chrome Android 18 Firefox Android 4 Opera Android 10.1 Safari iOS 1 Samsung Internet Android 1.0 nodejs 0.1.100
Stable sorting Chrome 70 Edge 79 Firefox 3 IE No Opera 57 Safari 10.1 WebView Android 70 Chrome Android 70 Firefox Android 4 Opera Android 49 Safari iOS 10.3 Samsung Internet Android 10.0 nodejs 12.0.0

图例

完整支持

完整支持

不支持

不支持

另请参阅

元数据

  • 最后修改:
  1. 标准内置对象
  2. Array
  3. 特性
    1. Array.prototype.length
    2. Array.prototype[@@unscopables]
  4. 方法
    1. Array.from()
    2. Array.isArray()
    3. Array.of()
    4. Array.prototype.concat()
    5. Array.prototype.copyWithin()
    6. Array.prototype.entries()
    7. Array.prototype.every()
    8. Array.prototype.fill()
    9. Array.prototype.filter()
    10. Array.prototype.find()
    11. Array.prototype.findIndex()
    12. Array.prototype.flat()
    13. Array.prototype.flatMap()
    14. Array.prototype.forEach()
    15. Array.prototype.includes()
    16. Array.prototype.indexOf()
    17. Array.prototype.join()
    18. Array.prototype.keys()
    19. Array.prototype.lastIndexOf()
    20. Array.prototype.map()
    21. Array.prototype.pop()
    22. Array.prototype.push()
    23. Array.prototype.reduce()
    24. Array.prototype.reduceRight()
    25. Array.prototype.reverse()
    26. Array.prototype.shift()
    27. Array.prototype.slice()
    28. Array.prototype.some()
    29. Array.prototype.sort()
    30. Array.prototype.splice()
    31. Array.prototype.toLocaleString()
    32. Array.prototype.toSource()
    33. Array.prototype.toString()
    34. Array.prototype.unshift()
    35. Array.prototype.values()
    36. Array.prototype[@@iterator]()
    37. get Array[@@species]
  5. 继承:
  6. Function
  7. 特性
    1. Function.arguments
    2. Function.caller
    3. Function.displayName
    4. Function.length
    5. Function.name
  8. 方法
    1. Function.prototype.apply()
    2. Function.prototype.bind()
    3. Function.prototype.call()
    4. Function.prototype.toSource()
    5. Function.prototype.toString()
  9. Object
  10. 特性
    1. Object.prototype.__proto__
    2. Object.prototype.constructor
  11. 方法
    1. Object.prototype.__defineGetter__()
    2. Object.prototype.__defineSetter__()
    3. Object.prototype.__lookupGetter__()
    4. Object.prototype.__lookupSetter__()
    5. Object.prototype.hasOwnProperty()
    6. Object.prototype.isPrototypeOf()
    7. Object.prototype.propertyIsEnumerable()
    8. Object.prototype.toLocaleString()
    9. Object.prototype.toSource()
    10. Object.prototype.toString()
    11. Object.prototype.valueOf()
    12. Object.setPrototypeOf()