Codecademy Practice

Address Book - Part 3

Challenge: In this part of the challenge we are going to sort columns in ascendant or descendant order.

When the page loads, the contacts will be unsorted. If the user clicks the title of a column, the contacts will be sorted by that column. If they click again, the contacts will be sorted in the reverse order, and so on.

In addition to that, everytime the user clicks, the arrow indicator will be updated to show if the rows are sorted in ascendant or descendant order, to inform the user on the current sorting order.

Things you’ll practice: Iterators, working with tables.

Example:

  (contacts table is displayed)
  Click on a column title
  Contacts get sorted by that column
  Click again
  Contacts get sorted in the reverse order
Video showing how searching contacts works.

Step by step instructions:

HTML

CSS

JS

We are going to use a mutator method to sort the rows according to the content of the cells that belong to the column to sort by. The mutator method can be used with or without passing a sorting function as an argument. We are going to pass a custom sorting function to the mutator method.

When we are done sorting, we’ll have to replace the rows of the table body with the sorted rows. We could use a loop for this, and add them one by one. However, when adding several elements one by one, the browser will redraw the layout every time, which has a performance impact. In this case it is recommended to use a document fragment, which is like a ghost document where you can append your elements without causing a reflow. Then you append the fragment to your actual document, so that the browser only redraws once.

Once we have done this, we should be able to click any column title and have the rows sorted. However, if we click the same column again, nothing happens. Let’s fix that.

GIT

Work in the same project but in a new branch. When the branch is ready create a pull request and ping me to review.

DEBUGGING

Use console.log() as usual.