Array sorting Method sort

Source: Internet
Author: User

<! DOCTYPE html>
<meta charset= "UTF-8" >
<title> Array Sorting </title>
<body>
<script>
Reverse () Inversion of array contents
eg:[1,2,,3,4,5] into [5,4,3,2,1]
Sort () arranges array items in ascending order by default, that is, the minimum value is first, the maximum value is in the last Face (the ToString () transformation method that calls each array item, and then the resulting string, even if each item in the array is a numeric value, and the comparison is also a string)
The sort () method can receive a function as an argument so that we specify which value in the front of the comparison function can receive two parameters if the first parameter should return a negative number before the second argument, two numbers equal return 0, if the first function returns a positive value after the second one
The sort () method changes the order of the original array
function Compare (value1,value2) {
if (value1 < value2) {
return-1;
}else if (value1 = = value2) {
return 0;
}else{
return 1;
}
}
var arr = [10,30,7,9,29];
Arr.sort (Compare);
Console.log (arr);
If you want a descending arrangement, just swap the return value for a second.

The second Method Example (this is an inverted method arrangement)
function Compare1 (value1,value2) {
return value2-value1;
}
var arr2 = [19,30,66,55,88,99];
Arr2.sort (Compare1);
Console.log (ARR2);
</script>
</body>

Array sorting Method sort

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.