Sort the array in js

Because the sort method in the array are ordered according to the js unicode value of the element, so that the size of the conventional digital sorting sort method can not be achieved, so we can use the callback function to sort the sort method.

Callback function to define two parameters, the browser uses the elements in the array as an argument to the callback function, respectively, the browser to determine the order of elements in accordance with the return value of the callback function.

  • If it returns a number greater than 0, then the element will exchange positions.
  • If it returns a number less than 0, the element position unchanged.
  • If it returns a 0, the two elements that are equal, nor the exchange position.

Therefore, from the above results:
If desired ascending order, ab & returns,
if desired in descending order, BA is returned.

Ascending:

arr = [5,4,2,1,3,7,8,6];
arr.sort(function(a,b){
	return a-b;
});

descending sort:

arr = [5,4,2,1,3,7,8,6];
arr.sort(function(a,b){
	return b-a;
});
Published 53 original articles · won praise 2 · Views 4315

Guess you like

Origin blog.csdn.net/qq_43126186/article/details/104648860