Home  >  Article  >  Web Front-end  >  Using the sort() method to sort array elements in JavaScript

Using the sort() method to sort array elements in JavaScript

高洛峰
高洛峰Original
2017-02-06 10:04:131926browse

The JavaScript array sort() method sorts the elements of the array.
Syntax

array.sort( compareFunction );

The following are the details of the parameters:

compareFunction: Specify a function and define the sort order. If omitted, the array is sorted lexicographically.

Return value:

Returns a sorted array
Example:

<html>
<head>
<title>JavaScript Array sort Method</title>
</head>
<body>
<script type="text/javascript">
var arr = new Array("orange", "mango", "banana", "sugar");
 
var sorted = arr.sort();
document.write("Returned string is : " + sorted );
 
</script>
</body>
</html>

This will produce the following results:

Returned array is : banana,mango,orange,sugar

For more related articles on using the sort() method to sort array elements in JavaScript, please pay attention to the PHP Chinese website!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn