The sort method for arrays in JS USES the example

  • 2020-03-30 01:26:46
  • OfStack

 
var values=[0,1,5,10,15]; 
values.sort(); 
alert(values);//0,1,10,15,5

This is because sort calls the toString method for each item to compare, and "10" is smaller than "5", so it comes first.
To sort the values, you need to define a comparison function and pass it into sort.
 
function compare(value1,value2){ 
if(value1<value2){ 
return -1; 
}else if(value1>value2){ 
return 1; 
}else{ 
return 0; 
} 
} 
var values=[0,1,5,10,15]; 
values.sort(compare); 
alert(values);//0,1,5,10,15

So this is going forward and this is going backwards just by swapping the negative 1 and the negative 1 in the comparison function.

Related articles: