you need to create an alternate sorting function and use it with the sort method. like this: <script type="text/javascript"> var arr=[7,5,3,1]; arr.sort(function(a,b) {return a-b}); document.write(arr); </script> Code (markup): The function created on line 2 returns a value to the sort method for each two numbers that it is comparing (a and b), a negative return value means a is lower then b, a positive return value means a is higher then b, and 0 means the two are equal. This allows the sort method to sort the values accordingly. You can change this to descending by changing: arr.sort(function(a,b) {return a-b}); to: arr.sort(function(a,b) {return b-a});
Thanks camjohnson95. Very good explanation of the sort function, that will come in handy in the future. However I asked for the wrong thing. I asked how to rearrange an array of numbers but what I actually wanted to do is keep them in the same order but output (document.write) them in ascending order. E.g. My array would be myArray=[5,2,6,1]. I want to keep them stored in this order, but to ouptut them as 1,2,5,6. The reason for this is I have an array of numbers and an array of names and they correspond to eachother. Obviously if I rearrange the numbers then the names will not correspond to the correct number. Thanks, Michael
<script type="text/javascript"> var arr=[7,3,5,1,8]; var arr2 = arr.concat(); arr2.sort(function(a,b) {return a-b}); document.write("Original: " + arr); document.write("<br>Sorted: " + arr2); </script> Code (markup):
alternatively you could have the name values and number values stored in the same array: <script type="text/javascript"> var arr = [{n: "Name1", num: 6},{n: "Name2", num: 3},{n: "Name3", num: 9},{n: "Name4", num: 5}]; arr.sort(function(a,b){return a.num-b.num}); for(i=0; i<arr.length;i++) { document.write("Name: " + arr[i].n + "<br>"); document.write("Number: " + arr[i].num + "<br>"); } </script> Code (markup):