Ez a fordítás nem teljes. Kérjük segítsen ezt a cikket lefordítani angolról.
A sort() eljárás egy tömb elemeit rendezi sorrendben, és visszaadja a tömböt. Egy rendezés nem teljesen Stabil. Az alapértelmezett rendezési sorrend,függ a sztring Unicode táblában való elhelyezkedésétől.
var fruits = ['cherries', 'apples', 'banana']; fruits.sort(); // ['apple', 'banana', 'cherries'] var scores = [1, 10, 21, 2]; scores.sort(); // [1, 10, 2, 21] // Figyeld meg,hogy a 10 a 2 előtt jön, // mivel a '10' hamarabb van,mint '2' a Unicode sorolás szerint. var things = ['word', 'Word', '1 Word', '2 Words']; things.sort(); // ['1 Word', '2 Words', '', 'word'] // A Unicode-ban, a számok hamarabb kerülnek sorra mint a nagybetűk, // de, azok hamarabb vannak,mint a kisbetűk.
Szintaxis
arr.sort() arr.sort(compareFunction)
Paraméterek
compareFunctionOptional- Meghatároz egy függvényt, amely definiálja a rendezési sorrendet. Ha elhagyjuk, a tömb rendezése az egyes betűk Unicode táblában való elhelyezkedése alapján történik meg.
Visszatérési érték
A rendezett tömb.
Leírás
Ha a compareFunction nem mellékelt, akkor az elemek rendezése úgy zajlik, hogy először átkonvertálja sztringgé, majd összehasonlítja a Unicode karakter sorrendet. Például, "Banana" hamarabb lesz,mint "cherry". Szám-sorrendben a 9 hamarabb lesz 80-nál, de mivel a számok átkonvertálódnak sztringgé, "80" hamarabb lesz "9"-nél a Unicode sorolás szerint.
Ha compareFunction mellékelt, a tömb elemei rendezésre kerülnek az összehasonlító függvény visszatérési értéke alapján. Ha a és b elemek összehasonlításra kerülnek:
- Ha
compareFunction(a, b)kisebb mint 0, akkor a kisebb indexet kap,mintb, szóval a előre kerül. - Ha
compareFunction(a, b)0-t ad vissza, akkor a-t és b-t hagyjuk változatlanul,de a többi elemet rendezzük. Megjegyzés: az ECMAscript szabvány nem garantálja ezt a viselkedést,és hogy nem minden böngésző (például: Mozilla verziók,melyek 2003 körüliek) támogatja. - Ha
compareFunction(a, b)nagyobb mint 0, rendezze b-t kisebb indexre mint a. compareFunction(a, b)mindig ugyanazt az értéket kellene visszaadja, amikor a jellemző a-b párost kapja meg paraméterként. Ha következetlen értéket ad vissza, akkor a rendezési sorrend "undefined".
Szóval, az összehasonlító függvény így néz ki:
function compare(a, b) {
if (a kisebb mint b a sorrend kritéria szerint) {
return -1;
}
if (a nagyobb mint b a sorrend kritéria szerint) {
return 1;
}
// a-nak egyenlőnek kell lennie b-vel
return 0;
}
To compare numbers instead of strings, the compare function can simply subtract b from a. The following function will sort the array ascending (if it doesn't contain Infinity and NaN):
function compareNumbers(a, b) {
return a - b;
}
The sort method can be conveniently used with function expressions (and closures):
var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
return a - b;
});
console.log(numbers);
// [1, 2, 3, 4, 5]
Objektumok is rendezhetőek, ha megadjuk az egyik tulajdonságát.
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(); // nagybetűk és kisbetűk elhagyása
var nameB = b.name.toUpperCase(); // nagybetűk és kisbetűk elhagyása
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// a neveknek egyeznie kell
return 0;
});
Példák
Tömbök készítése,megjelenítése és rendezése
A következő példa négy tömböt készít, megjeleníti az eredeti tömböt, majd a rendezett tömböket. A numerikus tömbök először nem,azután használva a compare függvényt rendezésre kerülnek.
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
Nem-ASCII karakterek rendezése
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', 'cliché', 'communiqué', 'café', 'adieu'];
items.sort(function (a, b) {
return a.localeCompare(b);
});
// items is ['adieu', 'café', 'cliché', 'communiqué', 'premier', 'réservé']
Rendezés map-al
The 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, the wiser it may be to consider using a map for sorting. The idea is to walk the array once to extract the actual values used for sorting into a temporary array, sort the temporary array and then walk 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) {
return +(a.value > b.value) || +(a.value === b.value) - 1;
});
// container for the resulting order
var result = mapped.map(function(el){
return list[el.index];
});
Specifications
| Specification | Status | Comment |
|---|---|---|
| ECMAScript 1st Edition (ECMA-262) | Standard | Initial definition. |
| ECMAScript 5.1 (ECMA-262) The definition of 'Array.prototype.sort' in that specification. |
Standard | |
| ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Array.prototype.sort' in that specification. |
Standard | |
| ECMAScript 2017 Draft (ECMA-262) The definition of 'Array.prototype.sort' in that specification. |
Draft |
Böngésző kompatibilitás
| Funkció | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Alap támogatás | 1.0 | 1.0 (1.7 or earlier) | 5.5 | (Yes) | (Yes) |
| Funkció | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Alap támogátás | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |