JavaScript custom array sorting method_javascript skills

Source: Internet
Author: User
This article mainly introduces the JavaScript custom array sorting method. The example analyzes the principle and implementation skills of javascript custom array sorting, which is of great practical value, for more information about how to sort arrays in JavaScript, see the following example. Share it with you for your reference. The specific analysis is as follows:

The Array has its own sorting function, which is convenient to use. we must be clear about the basis for sorting. If sort does not input parameters, it is encoded by character (Unicode).

Var a = ["3", "2", "1"]; console. log (a [0]. charCodeAt (0); // 51 console. log (a [1]. charCodeAt (0); // 50 console. log (a [2]. charCodeAt (0); // 49 console. log (. sort (); // ["1", "2", "3"] var a = ["3", "you", "he"]; console. log (a [0]. charCodeAt (0); // 51 console. log (a [1]. charCodeAt (0); // The 20320 console. log (a [2]. charCodeAt (0); // The 20182 console. log (. sort (); // ["3", "", ""] var a = ["3", "11", "222"]; console. log (. sort (); // ["11", "222", "3"] // first Character encoding

However, I think the best use of sort is that it can be customized for sorting, which is also common in practical use, such as sorting object arrays. For example, an array of objects on the line must be sorted by a field. of course, you can also write a function, but I don't think sort is convenient.

Var list = [{max: 3, avg: 2, min: 1}, {max: 10, avg: 15, min: 20}, {max: 8, avg: 5, min: 2}]; // sort list objects by the max field, from small to large order // x, y is a single element of the array to be compared, here is an element in the list // The sorting method is mainly to provide a relatively large rule, in other words, it means to indicate who is big and who is small. // The return value is true or false. function sortByField (x, y) {return x. max-y. max;} console. log (list. sort (sortByField ));

Shows the running effect:

I hope this article will help you design javascript programs.

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.