A detailed explanation of the array sort method in JavaScript

Source: Internet
Author: User
Tags array sort

When dealing with arrays, we sometimes need to sort the array, there are many ways to sort, but the best and quickest way is to use the sort method for fast sorting.

Let's take a look at an example:

The code is as follows Copy Code

var arr1 = [6, 3, 4, 1, 2, 5, 7, 3, 0, 9, 8, 10];//Here's an array of numbers.

Arr1.sort (function (a,b) {

return a-b;

});

This method is ascending to the platoon, whereas,

Arr1.sort (function (a,b) {

return b-a;

});

This is the descending method of defecation.

Sort by alphabetical

The code is as follows Copy Code

var arr = [' B ', ' CC ', ' abc ', ' Fzj ', ' xij ', ' ACD ', ' Yab '];
Arr.sort ();
for (var i = 0; i < arr.length; i++) {
Document.writeln (Namearr[i]);
}

Results: ABC ACD b cc Fzj Xij Yab

Demo2 numeric sort, sort (Prama) method with parameters

The code is as follows Copy Code

Descending function
var desc = function (x,y)
{
if (x > Y)
return-1; Returns a number less than 0.
Else
return 1; Returns a number greater than 0.
}
Ascending function
var asc = function (x,y)
{
if (x > Y)
return 1; Returns a number greater than 0.
Else
return-1; Returns a number less than 0.
}

var arr2 = [4,6,4,2,7,9,0,1];
Arr2.sort (DESC); Descending sort
Document.writeln (ARR2);
Document.writeln ("<br>");
Arr2.sort (ASC); Ascending sort
Document.writeln (ARR2);

Results:
9,7,6,4,4,2,1,0
0,1,2,4,4,6,7,9

A simple algorithm for Demo2

  code is as follows copy code

var arr2 = [ 4,6,4,2,7,9,0,1];   
Arr2.sort (function (a,b) {return a-b}); 
Document.writeln (ARR2);    
Document.writeln ("<br>");   
Arr2.sort (function (a,b) {return b-a}) ; 
Document.writeln (arr2);  
 
Result:

0,1,2,4,4,6,7,9
9,7,6,4,4,2,1,0 

Related Article

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: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.