JavaScript custom array sorting method _javascript tips

Source: Internet
Author: User

This example describes the JavaScript custom array sorting method. Share to everyone for your reference. The specific analysis is as follows:

Array has its own sorting function, which is convenient to use, we have a point must be clear, is the basis for sorting, if the sort does not pass in the parameters, it is in the order of character encoding (Unicode encoding) sequence.

var a=["3", "2", "1"]; 
Console.log (a[0].charcodeat (0)); Wuyi 
Console.log (a[1].charcodeat (0));// 
Console.log (a[2].charcodeat (0));// 
Console.log (A.sort ( ));      ["1", "2", "3"] 
 
var a=["3", "You", "he"]; 
Console.log (a[0].charcodeat (0)); Wuyi 
Console.log (a[1].charcodeat (0));//20320 
Console.log (a[2].charcodeat (0));//20182 
Console.log ( A.sort ());      ["3", "he", "you"] 
 
var a=["3", "One", "222"]; 
Console.log (A.sort ())//["One", "222", "3"]  
           //Multiple characters are encoded according to the first character

But I think the best thing about sort is that you can customize the sort, which is also more common in practice, such as ordering an array of objects. For example, a line of an object array, based on one of the fields sorted, of course, you can also write a function to complete, but I do not think that the sort came convenient.

var list = [ 
  { 
    max:3, 
    avg:2, 
    min:1 
  }, 
  { 
    max:10, 
    avg:15, 
    min:20 
  }, 
  { 
    Max:8, 
    avg:5, 
    min:2 
  } 
]; 
To sort the list objects by the Max field, the small to large order 
//X,y is the single element of the array to compare, here is an element 
//Sort method in the list is to provide a comparison of the size of the rules, in other words, is to show who the big and small 
//Return value is true or false 
function Sortbyfield (x, y) {returns 
  X.max-y.max; 
} 
Console.log (List.sort (Sortbyfield));

The effect is as shown in the following illustration:

I hope this article will help you with your JavaScript programming.

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.