23.04.2013 Views

javascript

javascript

javascript

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 6 ■ FUNCTIONS AND ARRAYS<br />

240<br />

So alrighty then, let’s save a function to a variable named sortByLosses that will sort pirates by<br />

losses. Begin by defining parameters named e1 and e2 for JavaScript to pass elements in pirates to<br />

sortByLosses() with.<br />

var pirates = [[2010, 57, 105],<br />

[2009, 62, 99],<br />

[2008, 67, 95],<br />

[2007, 68, 94],<br />

[2006, 67, 95],<br />

[2005, 67, 95],<br />

[2004, 72, 89],<br />

[2003, 75, 87],<br />

[2002, 72, 89],<br />

[2001, 62, 100],<br />

[2000, 69, 93],<br />

[1999, 78, 83],<br />

[1998, 69, 93],<br />

[1997, 79, 83],<br />

[1996, 73, 89],<br />

[1995, 58, 86],<br />

[1994, 53, 61],<br />

[1993, 75, 87]];<br />

var sortByLosses = function (e1, e2) {<br />

};<br />

Then write an if condition to handle the case where the Pirates lost the same number of games in<br />

e1 and e2. If so, we want to sort the seasons by year, putting the most recent season first. So we’ll have<br />

sortByLosses() return -1 if the year in e1[0] is more recent than e2[0], and 1 if e1[0] is more recent than<br />

e2[0]:<br />

var pirates = [[2010, 57, 105],<br />

[2009, 62, 99],<br />

[2008, 67, 95],<br />

[2007, 68, 94],<br />

[2006, 67, 95],<br />

[2005, 67, 95],<br />

[2004, 72, 89],<br />

[2003, 75, 87],<br />

[2002, 72, 89],<br />

[2001, 62, 100],<br />

[2000, 69, 93],<br />

[1999, 78, 83],<br />

[1998, 69, 93],<br />

[1997, 79, 83],<br />

[1996, 73, 89],<br />

[1995, 58, 86],<br />

[1994, 53, 61],<br />

[1993, 75, 87]];<br />

var sortByLosses = function (e1, e2) {<br />

if (e1[2] === e2[2]) {<br />

return e1[0] > e2[0] ? -1 : 1;<br />

}<br />

};

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

Saved successfully!

Ooh no, something went wrong!