Javascript - Array sort() Method

The sort() method sorts the array items.

Description

The sort() method sorts the array items.

By default, the sort() method sorts the values as strings in alphabetical and ascending order.

You can provide a "compare function" to implement the ordering among elements.

This method changes the original array.

Syntax

array.sort(compareFunction)

Parameter Values

ParameterRequire Description
compareFunction Optional. A function that defines an alternative sort order.

The function should return a negative, zero, or positive value, depending on the arguments.

Return

The Array object, with the items sorted

Example

Sort an array:

Demo

var myArray = ["XML", "Json", "Database", "Mango"];
console.log( myArray );/* www . j a  v a2  s . c  om*/

myArray.sort();
console.log( myArray );

//Sort numbers in an array in ascending order:

var points = [4, 10, 11, 5, 25, 10];
console.log( points );

points.sort(function(a, b){return a-b});
console.log( points );

//Sort numbers in an array in descending order:

var points = [4, 10, 1, 5, 25, 10];
console.log( points );

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];
console.log( points );

points.sort(function(a, b){return b-a});
console.log( points[0] );

//Get the lowest value in an array:

var points = [40, 100, 1, 5, 25, 10];
console.log( points );

points.sort(function(a, b){return a-b});
console.log( points[0] );

//Sort an array alphabetically, and then reverse the order of the sorted items (descending):

var myArray = ["XML", "Json", "Database", "Mango"];
console.log( myArray );

myArray.sort();
myArray.reverse();
console.log( myArray );

Result