TThe sort()
method sorts the items of an array.
The sort order can be either alphabetic or numeric, and either ascending (up) or descending (down).
By default, the sort()
method sorts the values as strings in alphabetical and ascending order.
This works well for strings ("Apple" comes before "Banana")
. However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".
Because of this, the sort()
method will produce an incorrect result when sorting numbers.
You can fix this by providing a "compare function" (See "Parameter Values" below).
Note: This method changes the original array.
// Sort Arrays Ascending using For loop
var myNumArray = [10,20,1,2,3];
for (var i = 0; i < myNumArray.length; i++){
for (var j = 0; j < i; j++){
if(myNumArray[i] < myNumArray[j]){
var x = myNumArray[i];
myNumArray[i] = myNumArray[j];
myNumArray[j] = x;
}
}
}
console.log(myNumArray);
// Sort numbers in an array in ascending order:
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});
console.log(points);
// Sort numbers in an array in descending order:
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b-a});
console.log(points);
// Get the highest value in an array:
var points = [40, 100, 1, 5, 25, 10];
// Sort the numbers in the array in descending order
points.sort(function(a, b){return b-a});
// The first item in the array (points[0]) is now the highest value
// Get the lowest value in an array:
var points = [40, 100, 1, 5, 25, 10];
// Sort the numbers in the array in ascending order
points.sort(function(a, b){return a-b});
// The first item in the array (points[0]) is now the lowest value
console.log(points[0]);
// Sort an array alphabetically, and then reverse the order of the sorted items (descending):
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
console.log(fruits);
fruits.reverse();
console.log(fruits);