C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Result: The array's elements are reordered. The string "abc" comes first as it is the earliest alphabetically.
JavaScript program that uses sort, string array
var patterns = ["def", "xyz", "abc"];
// Sort the string array.
patterns.sort();
console.log("SORTED: " + patterns);
Output
SORTED: abc,def,xyz
Tip: To keep the originally-ordered array around, a copy of the array would need to be made.
JavaScript program that shows sort modifies array
var patterns = ["def", "xyz", "abc"];
var result = patterns.sort();
// The original array is sorted.
console.log("VARIABLE 1: " + patterns);
console.log("VARIABLE 2: " + result);
Output
VARIABLE 1: abc,def,xyz
VARIABLE 2: abc,def,xyz
Here: We override the default sorting behavior with a function. In our function "compare" we sort two integers by their difference.
So: Numbers are sorted by their numeric values, and smaller numbers precede larger ones.
JavaScript program that uses sort, integer array
var numbers = [-1, 100, 10, 1, 2, 3];
// Numbers are sorted as strings by default.
numbers.sort();
console.log("SORT 1: " + numbers);
// This function sorts numbers.
// ... We compare two numbers by subtracting one from the other.
var compare = function(a, b) {
return a - b;
};
// Sort numbers in a numeric way.
numbers.sort(compare);
console.log("SORT 2: " + numbers);
Output
SORT 1: -1,1,10,100,2,3
SORT 2: -1,1,2,3,10,100
Here: We use localCompare to sort a string array from low to high (in ascending alphabetical order).
Then: We use a descending string sort. We compare the second string to the first in reverseAlphabetical.
Tip: It is possible to call reverse() after sorting a string array. But with localeCompare we can directly sort in reverse order.
JavaScript program that uses localeCompare
var unsorted = ["def", "xyz", "ghi", "abc"];
function alphabetical(a, b) {
// Use localeCompare.
return a.localeCompare(b);
}
function reverseAlphabetical(a, b) {
// Use localeCompare with second compared to first.
return b.localeCompare(a);
}
// Sort in alphabetical order.
unsorted.sort(alphabetical);
console.log("LOCALECOMPARE 1: " + unsorted);
// Sort in reverse alphabetical order.
unsorted.sort(reverseAlphabetical);
console.log("LOCALECOMPARE 2: " + unsorted);
Output
LOCALECOMPARE 1: abc,def,ghi,xyz
LOCALECOMPARE 2: xyz,ghi,def,abc