# Introduction to the use of the sort () method of arrays in JavaScript

Source: Internet
Author: User

The

Array's sort () method is used for sorting, and in this article you will introduce the specific use of the sort () method in JavaScript

The code is as follows: &lt;html&gt;&nbsp; &lt;head&gt;&nbsp; &lt;title&gt; Array Sort () method &lt;/title&gt;&nbsp; &nbsp; &lt;script&gt; &nbsp;/*&nbsp; sort () &nbsp; 1, no duplicates, direct reference to the original array &nbsp; 2, if the method is called without using parameters, the elements in the alphabetical array are sorted,&nbsp; more precisely, sorted in the order of character encoding. &nbsp; To do this, you should first convert the elements of the array into strings (if necessary) for comparison. &nbsp; &nbsp; 3, if you want to sort by other criteria, you need to provide a comparison function that compares two values,&nbsp; and then returns a number that describes the relative order of the two values. The &nbsp; comparison function should have two parameters A and B, and its return value is:&nbsp; if A is less than B, a value less than 0 is returned if a is in the sorted array before B. &nbsp; If a equals B, it returns 0. &nbsp; If a is greater than B, a value greater than 0 is returned. &nbsp; &nbsp; */&nbsp; &nbsp; var arr = [2,4,8,1,22,3];&nbsp; var arrsort= arr.sort ();//not sorted correctly, array first converted to string and then sorted &nbsp; Docu Ment.write ("The default sort array is:" + arrsort);//1,2,22,3,4,8&nbsp; document.write ("&lt;br/&gt;");&nbsp; &nbsp;//comparison function &nbsp; function Mysort (a,b) {&nbsp; return a-b;&nbsp;}&nbsp; &nbsp; var arrSort2 = Arr.sort (mysort);//Incoming comparison function &nbsp; document.write ("The array of incoming comparison parameters is:" + arrSort2);/Right Sort &nbsp; document.write ("&lt;br/&gt;");&nbsp; &nbsp; document.write (" The original array is: "+ arr);&nbsp; &nbsp; &lt;/script&gt;&nbsp; &nbsp; &Lt;/head&gt;&nbsp; &nbsp; &lt;body&gt;&nbsp; &lt;div id= "Time" &gt;&lt;/div&gt;&nbsp; &lt;/body&gt;&nbsp; &nbsp; &lt;/ html&gt;&nbsp;
Related Keywords:
Related Article

## E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

## Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

## Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth \$300-1200 USD