Write your own JavaScript's sort function

Source: Internet
Author: User

In the normal development we often encounter the sequence of the array to sort the scene, JS gives us the sort method can be sorted array elements, by default in alphabetical order by ASCII, see the following example:

var a = [1, 3, 2, 4];
var B = [' B ', ' A ', ' C ', ' d '];a.sort ();
// [1, 2, 3, 4]
Console.log (b); [' A ', ' B ', ' C ', ' d ']

But sometimes we need to define the sort requirements ourselves, and then we can pass a function to the sort function, using the custom collation, see the following example:

var a = [1, 3, 2, 4];a.sort (function  Compare (A, b) {   returnA;}); Console.log (a);   // [4, 3, 2, 1]

This is a simple custom example that sorts the array in descending order, for the function compare (a, b) {...} passed to the sort method, following a rule: If a positive number is returned, then A and b need to be exchanged, otherwise they will not be exchanged. Based on this criterion, we can make sure the exchange is based on our own needs. Take a look at the following code:

function Compare (A, b) {    if () {       /// If you do not want to exchange, return 1return         -1;    }     return 1;  // returns 1 to swap }

In this case A and B exchange or not exchange depends entirely on your own logic. You're the boss, Hee!!

If there is any wrong place, also ask you to correct your thighs!!!

Write your own JavaScript's sort function

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.