O'Reilly logo

jQuery and JavaScript Phrasebook by Brad Dayley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Sorting Arrays

arr1.sort(function(a,b){return a-b;}); ... arr1.sort(function(a,b){return Math.abs(a)-Math.abs(b);}); ... arr1.sort();

JavaScript provides a nice interface to sort arrays. The array object has a sort(function) method. The sort() method sorts the elements of the array in alphabetical order, converting elements to strings if possible, which is a problem for numerical arrays. You can specify your own sort function that accepts two elements and returns the following:

Image true or a positive number if the first value should be sorted higher

0 if they are equal

false or a negative number if the first value ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required