Sort JavaScript Arrays Ascending & Descending

By default, JavaScript has a sort function that takes the form of yourArrayName.sort( ) built-in, but to sort JavaScript arrays ascending and descending, you need a custom compare function to sort numeric values.

.sort() will work fine for strings since it sorts by the first character only, so Alpha will come before Beta, but when you sort 2, 18, 30 your output would be 18, 2 , 30 because 2 > 1 and 3 > 2.

To get around this quirk, you’d add a custom compare function as follows:

Sort JavaScript Arrays Ascending (a - b)

yourArrayName.sort(function(a, b){return a-b});

Sort JavaScript Arrays Descending (a+ b)

yourArrayName.sort(function(a, b){return a+b});

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *