Reorder methods Sort, reverse

Source: Internet
Author: User
Tags numeric value

Sort (): Arranges array items in ascending order, sort invokes the ToString () method of each array item, and then compares the string, determined how to sort, even if each item in the array is a numeric value, the string is compared;

Reverse (): Reverses the order of the array items;

Cases:

var values = [0,1,2,10,15,23,36];
Values.sort ();
Console.log (values);

Values.reverse ();
Console.log (values);

---output: (7) [0, 1, 10, 15, 2, 23, 36]

(7) [36, 23, 2, 15, 10, 1, 0]

Such a sort is not the best scenario in many cases, so the sort () method can accept a comparison function as an argument so that it is possible to specify which value is in front of which value.

A comparison function can accept two parameters, as follows:

function Compare (value1,value2) {
if (value1 < value2) return-1;
else if (value1 > value2) return 1;
else return 0;
}

var values = [0,1,5,10,15,23];
Values.sort (Compare);
Console.log (values);

---output: (6) [0, 1, 5, 10, 15, 23]

You can also do this in descending order, as long as the value returned by the interchange comparison function can be

function Compare (value1,value2) {ifreturn 1; Else if return -1; Else return 0;} var values = [0,1,5,10,15,23];values.sort (Compare); Console.log (values);

---output: (6) [23, 15, 10, 5, 1, 0]

Reorder methods Sort, reverse

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.