This is very easy to be done, because the JavaScript Array class has a method sort() that is exactely what we want.
What we have to do is just call sort() on blog before using it:
window.onload = function(evt) {
blog.sort();
showBlog(2);
// ...
This way of sorting could be enough sometimes, but not in our case. We sorted the array using the standard comparison algorithm applied to the first field in the array. So we have our blog ordered alphabetically by post title.
Hardly what we usually expect.
To specify a different field and a different sorting comparison we pass a function to the sort() method. This function has to accept in input two parameters, the two array items that are about to be compared, and return an integer that should be:
- less than zero if the first parameter should be before the second
- zero if they are considered equal
- greater than zero if the second parameter should be before the first
// older first
function compare1(post1, post2) {
return post1.date - post2.date;
}
// newer first
function compare2(post1, post2) {
return post2.date - post1.date;
}
We use that functions calling sort() like this:
blog.sort(compare);But can avoid creating a function that should be used just for one single call, and use a anonymous function. Here we choose to implement the "newer first" behaviour, that is the standard for blogs:
blog.sort(function(post1, post2) {return post2.date - post1.date;});
More information on the JavaScript Object Oriented features in chapter nine of Head First JavaScript. The code here is heavily based on an example you can find in this fun and useful book.
No comments:
Post a Comment