1. The principle of sorting data in javascript
The sort() method sorts the elements of the array in place and returns the array. sort may not be stable. By default, sort by Unicode code locations of the string;
Syntax: arr.sort([compareFunction])
Parameter compareFunction
Optional. Used to specify functions arranged in some order. If omitted, the elements are sorted by Unicode sites of the characters of the converted string.
If compareFunction(a, b) is less than 0, then a will be arranged before b;
If compareFunction(a, b) is equal to 0, the relative positions of a and b remain unchanged. Note: The ECMAScript standard does not guarantee this behavior, and not all browsers will comply with it.
If compareFunction(a, b) is greater than 0, b will be arranged before a.
//Sort the elements in the array in the order from small to large var arr=[11,55,22,45,16,87]; arr.sort(function(a,b){ return ab; }); console.log(arr);2. Simulate the principle of sorting data within JavaScript
sortSelf(arr,function(a,b){ return ab; }); console.log(arr); function sortSelf(array,fn){ for (var i = 0; i < array.length-1; i++) { var isSorted=true; //Sorted by default for (var j = 0; j < array.length-1-i; j++) { //Calling function if(fn(array[j],array[j+1])>0){ //Swap two variables var temp=array[j]; array[j]=array[j+1]; array[j+1]=temp; isSorted=false; } } if(isSorted){ break; } } }The above simulated sort sort (simple example) in JavaScript is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.