Hosting Solutions
mobile_logo Table of Contents


The sort() method of the Array object performs a sort on array elements. It is used to adjust the indexed order of elements in an array.

Syntaxarray.sort( compare_function )


compare_function (optional) An optional comparison function that evaluates each element in the array against the others. If return value is less than 0, put x on a lower index than y in the resulting array. If return value is equal to 0, leave x and y where they are. If return value is greater than 0, put y on a lower index than x in the resulting array.


Sorting strings var people = ["John","Robert","Alex"]; people.sort(); document.write(people); /* Alex,John,Robert */ Sorting numbers var nums = [2, 10, 4, 30]; nums.sort(); alert( nums ); /* 10,2,30,4 */ var nums = [2, 10, 4, 30]; function comparison(x, y) { return x - y; } nums.sort( comparison ); alert( nums ); /* 2,4,10,30 */