18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 12<br />

};<br />

return –1;<br />

} else if (value1 > value2) {<br />

return 1;<br />

} else {<br />

return 0;<br />

}<br />

As you can see, a comparison function compares two values, which is why a comparison function<br />

always has two arguments. If the first argument should come before the second argument, the function<br />

returns –1. If the first argument should come after the second argument, the function returns 1. If, however,<br />

the arguments are equal, the function returns 0. The comparison function is used in the sort()<br />

method like this:<br />

arr.sort(comparison_function);<br />

The basic comparison function pattern described previously sorts an array in ascending order. To sort in<br />

descending order, you just reverse 1 and –1:<br />

function comparison_function_desc(value1, value2) {<br />

if (value1 < value 2) {<br />

return 1;<br />

} else if (value1 > value2) {<br />

return -1;<br />

} else {<br />

return 0;<br />

}<br />

};<br />

If this pattern sounds familiar, that’s because the String’s localeCompare() method works the same<br />

way. So if you are sorting an array of strings, you can use this method directly:<br />

function compareStrings(string1, string2) {<br />

return string1.localeCompare(string2);<br />

}<br />

This function causes an array of strings to be sorted in ascending order. To sort an array in descending<br />

order, just put a negative sign in front of the call:<br />

function compareStringsDesc(string1, string2) {<br />

return -string1.localeCompare(string2);<br />

}<br />

By adding the negation operator, 1 becomes –1, –1 becomes 1, and 0 remains unchanged.<br />

Now, go back to the previous example, in which numbers are sorted incorrectly. You can easily remedy<br />

the problem by writing a comparison function that transforms the arguments into numbers first and<br />

then compares them:<br />

function compareIntegers(vNum1, vNum2) {<br />

var iNum1 = parseInt(vNum1);<br />

var iNum2 = parseInt(vNum2);<br />

368

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!