Home > Web Front-end > JS Tutorial > body text

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

高洛峰
Release: 2017-02-06 10:04:13
Original
1925 people have browsed it

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

array.sort( compareFunction );
Copy after login

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>
Copy after login

This will produce the following results:

Returned array is : banana,mango,orange,sugar
Copy after login

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


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!