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)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay