Saturday, February 23, 2013

Blog post 2/17

Sort method:

A good way to sort a list of names is to use this method, which sorts things alphabetically. Here's a good example:

//Sort alphabetically and ascending:
var myarray=["Bob", "Bully", "Amy"]
myarray.sort() //Array now becomes ["Amy", "Bob", "Bully"]

However, if you wanted to sort in descending order, you would use array.reverse() instead:

//Sort alphabetically and descending:
var myarray=["Bob", "Bully", "Amy"]
myarray.sort()
myarray.reverse() //Array now becomes ["Bully", "Bob", "Amy"]


With numbers, sorting them numerically and ascending would go something like this: 

var myarray=[25, 8, 7, 41]
myarray.sort(function(a,b){return a - b}) //Array now becomes [7, 8, 25, 41]


Sorting them numerically and descending would go something like this:

var myarray=[25, 8, 7, 41]
myarray.sort(function(a,b){return b - a}) //Array now becomes [41, 25, 8, 71]


Say you wanted to sort the order of the items in an array randomly. Here's an example on how to do that:

var myarray=[25, 8, "George", "John"]
myarray.sort(function() {return 0.5 - Math.random()}) //Array elements now scrambled



No comments:

Post a Comment