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 ...

Get jQuery and JavaScript Phrasebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.