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

Source: Internet
Author: User
Tags array sort arrays comparison


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

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

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

Learn more >

Alibaba Cloud Free Trial

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

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.