This article describes the JavaScript custom array sorting method. Share it for your reference. The specific analysis is as follows:
Array has its own sorting function, which is more convenient to use. One thing we must be clear about is the basis for sort. If sort does not pass parameters, it is sorted in the order of character encoding (Unicode encoding).
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(a.sort()); // ["1", "2", "3"] var a=["3","you","he"]; console.log(a[0].charCodeAt(0)); // 51 console.log(a[1].charCodeAt(0)); // 20320 console.log(a[2].charCodeAt(0)); // 20182 console.log(a.sort()); // ["3", "he", "you"] var a=["3","11","222"]; console.log(a.sort()); // ["11", "222", "3"] // Encoding the first character when multiple characters are used
However, I think the best thing about sort is that it can customize the sorting, which is also common in actual use, such as sorting object arrays. For example, an array of objects in a line surface must be sorted according to one of the fields. Of course, you can also write a function to complete it, but I think it is not convenient for sort.
var list = [ { max:3, avg:2, min:1 }, { max:10, avg:15, min:20 }, { max:8, avg:5, min:2 } ]; // Sort the list object according to the max field, in the order from small to large// x,y is a single element of the array to be compared, here is an element in the list// The sorting method mainly provides a rule to compare sizes, in other words, to indicate who is bigger and who is smaller// The return value is true or false function sortByField(x, y) { return x.max - y.max; } console.log(list.sort(sortByField));The operation effect is shown in the figure below:
I hope this article will be helpful to everyone's JavaScript programming.