[JS Basics] array sorting of JS

Source: Internet
Author: User

Simple array sorting

The definition of a simple array here is that the elements of the data are basic types such as integer, floating-point, and object type.

The sorting method is simple. Use the sort method of the array. The default value is ascending.

Example:

  <script>     var jsArray = [100,2,4,30];     jsArray.sort();     alert(jsArray);  </script>

The output result is:

100,2, 30,4

The result is different from what we expected because the sort method is sorted in ascii alphabetic order by default, rather than by number size.

For this method, pay special attention to the following:

1. When an array calls the sort method, it will affect itself (instead of generating a new array)

2. The sort () method is sorted by characters by default. Therefore, when sorting a numeric array, you cannot take it for granted that it will be sorted by number size!


Sort by custom sorting rules

You can use custom sorting rules to sort the preceding numeric arrays.

Is to give a sort function parameter to the sort method.

jsArray.sort(function(a,b){return a>b?1:-1});

The preceding steps are sorted in ascending order. If you want to sort them in descending order, it is very simple:
jsArray.sort(function(a,b){return a<b?1:-1});


Sorting of object arrays

The sorting of object arrays is generally based on the values of one or more keys in the object.

With the above introduction to sorting by custom sorting rules, it is not difficult to sort object arrays.

For example:

    var  jsArray = [{id:1,score:100},                {id:2,score:2},                {id:3,score:4},                {id:4,score:30}];     jsArray.sort(function(a,b){return a["score"]>b["score"]?1:-1});             //test        for(var i=0;i<jsArray.length;i++)     {        alert(jsArray[i].score);     }  


More

In fact, this usage of custom sorting rules is not uncommon. This method is often used in java for sort, and a word-comparator is often mentioned.

In fact, this comparison function is a comparator. when I introduced this to non-developers, they felt very worships with the word "device" ^. the common point is the comparison function ......

The following is a method for constructing a comparator with % data:

/************************************************* NAME:jsDataWithPercentComparator* DESCRIPTION:comparate data with Percent like {key1:'1.2%'}* ARGUMENTS:*sortField  --> one key of js object*sortType  -->desc or asc , default is asc* AUTHOR: oscar999*************************************************/function getJsPercentDataComparator(sortField,sortType){var thisSortType = "asc";if(sortType!=null&&(sortType=="asc"||sortType=="desc")){thisSortType = sortType;}if(thisSortType=="asc"){return function(a,b){var result = 0;if(a[sortField]!=null&&b[sortField]!=null){var astring = a[sortField].replace(/%/,"");var bstring = b[sortField].replace(/%/,"");var afloat = parseFloat(astring);var bfloat = parseFloat(bstring);result = (afloat>bfloat)?1:-1;}return result;};}else if(thisSortType=="desc"){return function(a,b){var result = 0;if(a[sortField]!=null&&b[sortField]!=null){var astring = a[sortField].replace(/%/,"");var bstring = b[sortField].replace(/%/,"");var afloat = parseFloat(astring);var bfloat = parseFloat(bstring);result = (afloat<bfloat)?1:-1;}return result;};}}

Call test:
var array1  = [{key1:"28.2%"},{key1:"18.2%"},{key1:"38.2%"}];var comparator = getJsPercentDataComparator("key1",sortType);array1 = array1.sort(comparator);







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.