DEV Community

Rakshith holla
Rakshith holla

Posted on

JavaScript number sorting using default sort method

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;
});
Enter fullscreen mode Exit fullscreen mode

descending order or reverse sorting

array_name.sort(function(a, b){
  return b - a;
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)