Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial

Jonathan Rodríguez Ferreira
6,075 PointsSorting alphabetically a table using jQuery
Hello!
I'm on the Front End Development track and in the HTML Tables Course Nick Pettit suggested us to add jQuery to a table so we can sort and filter it.
I made a table and stored it elements by columns on different arrays. And I appended a button to sort the names alphabetically. It does it using the sort() method, but I don't know how to replace the existing content with the sorted one.
HTML Code for the table.
<code>
<table>
<caption>Employee working results</caption>
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Position</th>
<th scope="col">WHours/week</th>
<th scope="col">Cost</th>
<th scope="col">Profit</th>
</tr>
</thead>
<tbody>
<tr>
<td>James Smith</td>
<td>C.E.O.</td>
<td>50</td>
<td>6000</td>
<td>20000</td>
</tr>
<tr>
<td>John Johnson</td>
<td>Senior Vice President</td>
<td>45</td>
<td>4000</td>
<td>10000</td>
</tr>
<tr>
<td>Robert Williams</td>
<td>Vice president</td>
<td>45</td>
<td>4000</td>
<td>15000</td>
</tr>
</tbody>
</table>
</code>
JavaScript code
var numberOfRows = $("tr:nth-child(n+1):not(:first)").length; // 3
var names = [];
var jobPositions = [];
var workingHours = [];
var costs = [];
var profits = [];
$("table").append("<button id='sortNames'>Sort names alphabetically</button>");
//Sort the elements inside a table
//Select elements inside the column.
//Select name.
//Select the first <td> inside each <tr> in the <tbody>.
for (var i = 0; i < numberOfRows; i += 1) {
//Store the elements.
names = $("tbody td:first-child").map( function() {
return $(this).text();
});
};
//Sort it alphabetically.
$("#sortNames").click( function() {
namesSorted = names.sort();
$("tbody td:nth-child(1)").empty();
$("tbody td:nth-child(1)").append(namesSorted);
});
I know with this code I will not follow DRY rules, but first I want to make it work, because I am a newbie with this.
Someone could help me progress with this project? :)
3 Answers

LaVaughn Haynes
12,397 PointsI have not taken that course so I don't know if Nick provided specific instructions or if it's just up to you to figure out a solution but here are a few suggestions and an example.
- Your rows are already in order so I would start with them out of order so you know if your sort works
- One option is to remove the old rows and append the sorted rows
- I think you should sort the array of rows and not the text in the row because you can't append the sorted text. You will eventually have to append elements
- Appending the button puts it inside the table. I would insert after or create a container and append it to that
This is one solution:
<!DOCTYPE html>
<html>
<head>
<title>Sign Up Form</title>
<style>
</style>
</head>
<body>
<table>
<caption>Employee working results</caption>
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Position</th>
<th scope="col">WHours/week</th>
<th scope="col">Cost</th>
<th scope="col">Profit</th>
</tr>
</thead>
<tbody>
<tr>
<td>Robert Williams</td>
<td>Vice president</td>
<td>45</td>
<td>4000</td>
<td>15000</td>
</tr>
<tr>
<td>John Johnson</td>
<td>Senior Vice President</td>
<td>45</td>
<td>4000</td>
<td>10000</td>
</tr>
<tr>
<td>James Smith</td>
<td>C.E.O.</td>
<td>50</td>
<td>6000</td>
<td>20000</td>
</tr>
</tbody>
</table>
<script src="http://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript" charset="utf-8"></script>
<script>
//vars (cache elements)
var $table = $('table');
var $tableBody = $table.find('tbody');
var $button = $("<button></button>", { id: 'sortNames', text: 'Sort names alphabetically'});
var rows, sortedRows;
// add the button after the table
$button.insertAfter( $table );
//sort the table row based on the text of the first div
function sortRows(a, b){
if ( $(a).find('td:first-Child').text() > $(b).find('td:first-Child').text() ) {
return 1;
}
if ( $(a).find('td:first-Child').text() < $(b).find('td:first-Child').text() ) {
return -1;
}
return 0;
}
// when the button is clicked...
$button.on('click', function(){
//get the rows from the table
rows = $tableBody.find('tr');
//sort the rows as "sortedrows"
sortedRows = rows.sort(sortRows);
//replace the old rows with the new rows
$tableBody.remove('tr');
$tableBody.append(sortedRows);
});
</script>
</body>
</html>
If you want to go further you can figure out how to sort by multiple columns

Robert Richey
Courses Plus Student 16,352 PointsAdding to LaVaughn's answer (and borrowing some of his code), here's my take on the JavaScript portion. It includes being able to sort by ascending as well as descending.
var $table = $("table");
var $tableBody = $table.find("tbody");
var $buttonSortAscending = $("<p><button id='sortAscending'>Sort Rows by Name (ascending)</button></p>");
var $buttonSortDescending = $("<p><button id='sortDescending'>Sort Rows by Name (descending)</button></p>");
var rows, sortedRows, firstName, secondName, sortAscending;
$("body").append($buttonSortAscending);
$("body").append($buttonSortDescending);
var $buttons = $("button");
// one function to handle both ascending and descending sorts
function cmp(a, b) {
firstName = $(a).find('td:first-child').text();
secondName = $(b).find('td:first-child').text();
if (firstName < secondName) { return (sortAscending) ? -1 : 1 }
else if (firstName > secondName) { return (sortAscending) ? 1 : -1 }
else { return 0 }
}
function updateData() {
$tableBody.remove('tr');
$tableBody.append(sortedRows);
}
$buttons.click(function() {
rows = $tableBody.find("tr");
if ($(this).attr('id') === 'sortAscending') { sortAscending = true }
else { sortAscending = false }
sortedRows = rows.sort(cmp);
updateData();
})

geoffrey
28,736 PointsIt's cool you try to sort the table yourself, with your own code. What I would do If I were you is use the JQuery table sorter Plugin. It's very powerful and easy to set up, I've already used in in some projects. If I tell this It's because if we read the extrat credit in the course you watched it says:
If you continue to learn about front-end development, try adding some jQuery to your table. With the right plugin, you can add features like sorting and filtering to an otherwise static table.
On the other hand, I really appreciate your effort to do this on your own, that's the best way to learn.

LaVaughn Haynes
12,397 PointsAbsolutely. There is certainly value in learning how to use the plugins as well. When I first started I probably used plugins exclusively. It was a good long while before I tried to build the functionality myself like Jonathan. But I do think that working with the plugins helped solidify my understanding of what was going on. Plus sometimes the plugin is going to be better and faster to implement than what I can do, like this one http://gionkunz.github.io/chartist-js/

Robert Richey
Courses Plus Student 16,352 PointsThanks for sharing that - works like a charm. Clarifying a point made by the author, Christian Bach:
"To use the tablesorter plugin, include the jQuery library and the tablesorter plugin inside the <head> tag of your HTML document"
These work fine when placed at the end of the body tag, as well.
Also, don't forget that you need one of the css themes - green or blue.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="path/to/themes/blue/style.css">
</head>
<body>
<!-- table -->
<script src="path/to/jQuery"></script>
<script src="path/to/tablesorter.js"></script>
<script src="your/custom/script.js"></script>
</body>
</html>
The ability to shift-click a column to get multi-column sorting is really awesome. I'm definitely putting this library in my toolbox.

Jonathan Rodríguez Ferreira
6,075 PointsAbsolutely. I was trying just tu push my (yet) limited skills in JavaScript, just for fun and for learning new stuff. I will take into account your advice. Thanks for sharing :)
Jonathan Rodríguez Ferreira
6,075 PointsJonathan Rodríguez Ferreira
6,075 PointsThank you! You are right, I was appending my button to the table. Your solution seems quite easy to understand. I'll take a further look into it, it looks quite promising :)