JavaScript has a default sort function which can be used to sort a list of values.
usage -> array_name.sort();
However, this sort method returns incorrectly for numbers, since this considers all values as string and sorts the list of numbers by comparing with the ASCII value of the individual values.
This can be resolved by using comparison inside of the sort method.
ascending order sorting
array_name.sort(function(a, b){
return a - b;
});
descending order or reverse sorting
array_name.sort(function(a, b){
return b - a;
});
Top comments (0)