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.