Javascript array sorting and javascript sorting

Source: Internet
Author: User
Tags javascript array

Javascript array sorting and javascript sorting

If you have been using javascript for a while, you must know that the array sorting function sort is a method in the array prototype, that is, array. prototype. sort (), sort (compareFunction), where compareFunction is a comparison function. Let's look at a description from Mozilla MDN:
If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in lexicographic ("dictionary" or "telephone book," not numerical) order. for example, "80" comes before "9" in lexicographic order, but in a numeric sort 9 comes before 80.

Here are some simple examples:

Copy codeThe Code is as follows:
// Output [1, 2, 3]
Console. log ([3, 2, 1]. sort ());

// Output ["a", "B", "c"]
Console. log (["c", "B", "a"]. sort ());

// Output [1, 2, "a", "B"]
Console. log (["B", 2, "a", 1]. sort ());


As shown in the preceding example, It is sorted by letters in the dictionary by default.

Fortunately, sort accepts a custom comparison function, as shown in the following example:

Copy codeThe Code is as follows:
Function compareFunction (a, B ){
If (a> B ){
Return-1;
} Else if (a <B ){
Return 1;
} Else {
Return 0;
}
}
// Outputs ["zuojj", "Benjamin", "1"]
Console. log (["Benjamin", "1", "zuojj"]. sort (compareFunction ));

After sorting, we have another question: how can we control ascending and descending order?

Copy codeThe Code is as follows:
Function compareFunction (flag ){
Flag = flag? Flag: "asc ";
Return function (a, B ){
If (a> B ){
Return flag = "desc "? -1: 1;
} Else if (a <B ){
Return flag = "desc "? 1:-1;
} Else {
Return 0;
}
};
}
// Outputs ["1", "Benjamin", "zuojj"]
Console. log (["Benjamin", "1", "zuojj"]. sort (compareFunction ()));
// Outputs ["zuojj", "Benjamin", "1"]
Console. log (["Benjamin", "1", "zuojj"]. sort (compareFunction ("desc ")));

The comparFunction sorting rules are as follows:
1. If it returns a negative number, a will be sorted to a lower index in the array.
2. If it returns a positive number, a will be sorted to a higher index.
3. And if it returns 0 no sorting is necessary.

Let's take a look at a passage from Mozilla MDN:
The behavior of the sort method changed between JavaScript 1.1 and JavaScript 1.2.To explain this description, let's look at an example:

In JavaScript 1.1, on some platforms, the sort method does not work. This method works on all platforms for JavaScript 1.2.

In JavaScript 1.2, this method no longer converts undefined elements to null; instead it sorts them to the high end of the array. For details, click here.

Copy codeThe Code is as follows:
Var arr = [];
Arr [0] = "Ant ";
Arr [5] = "Zebra ";
// Outputs ["Ant", 5: "Zebra"]
Console. log (arr );
// Outputs 6
Console. log (arr. length );
// Outputs "Ant ***** Zebra"
Console. log (arr. join ("*"));
// Sort
Var sortArr = arr. sort ();
// Outputs ["Ant", "Zebra"]
Console. log (sortArr );
// Outputs 6
Console. log (sortArr. length );
// Outputs "Ant * Zebra ****"
Console. log (sortArr. join ("*"));

I hope this article will help you learn and understand the sort () method, and I hope you will criticize the sort () method.

Reference: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/sort


Sort arrays by javascript

Arr. sort (sortNumber)
Arr. sort (): A system function that processes two adjacent elements in the arr array.
SortNumber is a custom sorting condition.
Because the sorting condition of the sort () function is: if the parameter is greater than 0, the adjacent two elements of the arr are switched;
If the parameter is smaller than 0, the adjacent two elements of arr do not swap positions;
The parameter is equal to 0, and the size of two adjacent elements of arr is equal. Therefore, the sortNumber UDF must return a value.
(A-B) indicates that two adjacent elements subtract the last element from the first element. return the value. The sort () function determines whether the two elements of arr exchange positions based on the positive and negative values.
B-a is in reverse order. This means that B-a indicates that two adjacent elements are subtracted from the previous element according to the last element. return the value. The sort () function determines whether the two elements of arr exchange positions based on the positive and negative values.

Javascript array sorting

Reading the above section of your code is helpful to you.

Description
If no parameter is used when this method is called, the elements in the array are sorted alphabetically. More precise, the elements are sorted by character encoding. To achieve this, first convert the elements of the array into strings (if necessary) for comparison.

If you want to sort by other criteria, you need to provide a comparison function that compares two values and returns a number indicating the relative sequence of the two values. The comparison function should have two parameters, a and B. The returned values are as follows:

If a is less than B, a should appear before B in the sorted array, then a value smaller than 0 is returned.
If a is equal to B, 0 is returned.
If a is greater than B, a value greater than 0 is returned.
Reference: w3school

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.