The sort method in a JavaScript array

Source: Internet
Author: User
Tags javascript array

This is also generally recommended in the way, because you do not know what the different JS engine will not pass the sorting function, according to what scheme to sort.
For example:

The code is as follows Copy Code

var colors = [' red ', ' green ', ' blue ', ' yellow ', ' white '];
Console.log (Colors.sort ()); ["Blue", "green", "red", "white", "yellow"]
Console.log (colors); ["Blue", "green", "red", "white", "yellow"]

If you do not pass the sort function, then, for strings, they are sorted alphabetically, but what if there is a combination of uppercase and lowercase letters in those strings?

The code is as follows Copy Code

var colors = [' red ', ' green ', ' blue ', ' yellow ', ' white '];
Console.log (Colors.sort ()); www.111cn.net ["White", "yellow", "blue", "green", "red"]

What, the results are different? This is because they are sorted in ASCII-encoded order at this time.

Also, another problem is that the sort function works on the original array, and that is, the result of the sort overrides the array before the sort.

Then, for a numeric array, what happens if you don't pass the sort function?

The code is as follows Copy Code

var money = [12, 3, 7.4, 200];
Console.log (Money.sort ()); [12, 200, 3, 7.4]

Hey? Do not get the expected results (unless your expectations are not the size of the numbers), then why?

Because when sorting is sorted, if you don't pass the sort function, you first convert all the elements to strings, and then the sort of one word (ASCII, which is the same for true or false), and why are all converted to strings because JavaScript An array can be any type of data, so JavaScript cannot infer exactly what type of transformation to sort.

So let's look at the different data types, some of the ways to sort the functions:

The array is all numbers, or is expected to be sorted by number.

The code is as follows Copy Code
var money = [12, 3, 7.4, 200];
var compare = function (A, b) {return a-b;};
Console.log (Money.sort (Compare)); [3, 7.4, 12, 200]
Console.log (Money.sort (function (A, b) {return a-b;})); [3, 7.4, 12, 200]

This is the most basic sort of function, and any place that talks about JavaScript sorting will basically say this. First two elements are assigned to a B, return the value of a-b, if a negative is returned a before B, equal to 0 does not matter, because two elements are equal, return integrity, then a after B.

For the elements of a string, just like the number, it's a different sort function, what if it's an object?

The code is as follows Copy Code

var people = [
{
Name: ' Alice ',
id:1234
},
{
Name: ' Bob ',
id:567
}
];
var compare = function (A, b) {return a.id-b.id}
Console.log (People.sort (Compare)); Bob is before Alice now

The parameters that are passed by the sort function of the element are the same, the elements in the two arrays, and then the values of the IDs of the two object elements are mainly compared for sorting.

But what if the following situation is true?

The code is as follows Copy Code

var everything = [4, ' Red ', ' $ ', ' white ', 7.4, true, 0.3, false];
var compare = function (A, b) {return a-b;};
Console.log (Everything.sort (Compare));

When the sort function is computed, it is converted to a number for calculation because of the participation of subtraction, but if it is a string, it will be translated to NaN because there is no explicit definition in the ECMA specification as to how this should be sorted, so each platform That is, the different browsers (JavaScript environment), resulting in the final result will not necessarily be the same. You can test them on a different browser.

Let's put a few of your own sort sort examples here

The code is as follows Copy Code

<title> Array's sort () method </title>

<script>
/*
Sort ()
1, does not produce a copy, direct reference to the original array
2. If you call the method without using parameters, the elements in the array are sorted alphabetically.
To be more precise, sorting is done in the order of character encoding.
To do this, you should first convert the elements of the array into strings (if necessary) for comparison.

3, if you want to sort by other standards, you need to provide a comparison function, the function to compare two values,
It then returns a number that describes the relative order of the two values.
The comparison function should have two parameters A and B, and the return value is as follows:
If a is less than B, a value less than 0 is returned in the sorted array before a should appear in B.
If a equals B, it returns 0.
If a is greater than B, a value greater than 0 is returned.

*/

var arr = [2,4,8,1,22,3];
var arrsort= arr.sort ();//not sorted correctly, the array is converted to a string and then sorted
document.write ("The default sort array is:" + arrsort);//1,2,22,3,4,8
document.write ("<br/>");

comparison function
function Mysort (a,b) {
return a-b;
}

var arrSort2 = Arr.sort (mysort);//Incoming comparison function
document.write ("The array of incoming comparison parameters is:" + arrSort2);
document.write ("<br/>");

document.write ("Original array is:" + arr);

</script>


<body>
<div id= "Time" ></div>
</body>

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.