Sort

The sort algorithm sorts an array in place. This means that, when the sort() method is used, the original array is replaced with the sorted one. The closure takes two arguments (represented by $0 and $1), and it should return a Boolean value that indicates whether the first element should be placed before the second element. The following code shows how to use the sort algorithm:

var arrayOne = [9,3,6,2,8,5]
arrayOne.sort(){ $0 < $1 } //arrayOne contains 2,3,5,6,8 and 9

The preceding code will sort the array in ascending order. We can tell this because the rule will return true if the first number ($0) is less than the second number ($1). Therefore, when the sort algorithm begins, it compares the first two numbers (9 and 3) and returns true if the first number (9) is less than the second number (3). In our case, the rule returns false, so the numbers are reversed. The algorithm continues sorting in this manner until all of the numbers are sorted in the correct order.

The preceding example sorted the array in numerically increasing order; if we wanted to reverse the order, we would reverse the arguments in the closure. The following code shows how to reverse the sort order:

var arrayOne = [9,3,6,2,8,5]  
arrayOne.sort(){ $1 < $0 } 
//arrayOne contains 9,8,6,5,3 and 2 

When we run this code, arrayOne will contain the elements 9, 8, 6, 5, 3, and 2.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset