Arranging items in order is a frequent need when dealing with arrays. For example, you might want to arrange a list of city or country names alphabetically.
The JavaScript Array object comes with a built-in method called sort()
for organizing array elements alphabetically. The following example illustrates its usage:
var fruits = ["Banana", "Orange", "Apple", "Papaya", "Mango"];
var sorted = fruits.sort();
alert(fruits); // Outputs: Apple,Banana,Mango,Orange,Papaya
alert(sorted); // Outputs: Apple,Banana,Mango,Orange,Papaya
To reverse the sequence of elements in an array, you can employ the reverse()
method.
When applied, this method flips the array so that the initial element becomes the final one, and vice versa. Here's a demonstration:
var counts = ["one", "two", "three", "four", "five"];
var reversed = counts.reverse();
alert(counts); // Outputs: five,four,three,two,one
alert(reversed); // Output: five,four,three,two,one
Note: Both the sort()
and reverse()
methods alter the original array and return a reference to the same array, as demonstrated in the examples above.
When the sort()
method is used on numeric arrays (i.e., arrays containing numeric values), it may yield unexpected results. For example:
var numbers = [5, 20, 10, 75, 50, 100];
numbers.sort(); // Sorts numbers array
alert(numbers); // Outputs: 10,100,20,5,50,75
As you can observe, the outcome differs from our expectation. This occurs because the sort()
method arranges the numeric array elements by converting them to strings (e.g., 20 becomes "20", 100 becomes "100", and so forth). Consequently, since the first character of the string "20" (i.e., "2") appears after the first character of the string "100" (i.e., "1"), the value 20 is sorted after 100.
To resolve this sorting issue with numeric arrays, you can provide a comparison function, like this:
var numbers = [5, 20, 10, 75, 50, 100];
// Sorting an array using compare function
numbers.sort(function(a, b) {
return a - b;
});
alert(numbers); // Outputs: 5,10,20,50,75,100
As you can observe, this time we've obtained the correct result. Let's delve into how it operates.
When a comparison function is specified, array elements are sorted based on the return value of the comparison function. For instance, when comparing a
and b
:
a
comes first.b
comes first.a
and b
remain unchanged with respect to each other, but are sorted with respect to all other elements.Therefore, since 5 - 20 = -15
, which is less than 0, 5 comes first. Similarly, 20 - 10 = 10
, which is greater than 0, so 10 comes before 20. Likewise, 20 - 75 = -55
, which is less than 0, so 20 comes before 75. Similarly, 50 comes before 75, and so on.
You can utilize the apply()
method in conjunction with Math.max()
and Math.min()
to determine the maximum and minimum values within an array, as shown below:
var numbers = [3, -7, 10, 8, 15, 2];
// Defining function to find maximum value
function findMax(array) {
return Math.max.apply(null, array);
}
// Defining function to find minimum value
function findMin(array) {
return Math.min.apply(null, array);
}
alert(findMax(numbers)); // Outputs: 15
alert(findMin(numbers)); // Outputs: -7
The apply()
method offers a convenient way to pass array values as arguments to a function that accepts multiple arguments in an array-like manner, although not directly as an array (e.g., in Math.max()
and Math.min()
methods). Therefore, the resulting statement Math.max.apply(null, numbers)
in the example above is equivalent to Math.max(3, -7, 10, 8, 15, 2)
.
The sort()
method can also be employed to sort arrays of objects using a comparison function.
The following example demonstrates how to sort an array of objects based on property values:
var persons = [
{ name: "Harry", age: 14 },
{ name: "Ethan", age: 30 },
{ name: "Peter", age: 21 },
{ name: "Clark", age: 42 },
{ name: "Alice", age: 16 }
];
// Sort by age
persons.sort(function (a, b) {
return a.age - b.age;
});
console.log(persons);
// Sort by name
persons.sort(function(a, b) {
var x = a.name.toLowerCase(); // ignore upper and lowercase
var y = b.name.toLowerCase(); // ignore upper and lowercase
if(x < y) {
return -1;
}
if(x > y) {
return 1;
}
// names must be equal
return 0;
});
console.log(persons);