Created
January 23, 2014 16:42
-
-
Save slopeofhope81/8582024 to your computer and use it in GitHub Desktop.
How to write a reverse function on an array that has integers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Do you know that the sort method does not work so well on integers in an array since it is used for strings! | |
That is something I found out today so then how to use a sort method on an array that has integers? Simply add a | |
custom function to a sort method as an argument like below! | |
var arr = [1,100,4,30,5,80] | |
var compare = function(num1,num2){ | |
if (num1 < num2){ | |
return -1; | |
} | |
else if (num1 > num2){ | |
return 1; | |
} | |
else{ | |
return o; | |
} | |
} | |
then run the following method using the compare variable as an argument in the sort method like below! | |
document.write(arr.sort(compare)) | |
Then how would you modify this code so that the array goes from the highest # to the lowest? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment