<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Sort plugin for jQuery</title>
</head>
<body>
<h1>Demo</h1>
<p>Click on the headers (fruit/quantity).</p>
<table>
<thead>
<tr>
<th>Fruit</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td>Grape</td>
<td>15</td>
</tr>
<tr>
<td>Apple</td>
<td>4</td>
</tr>
</tbody>
</table>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="jquery.sort.js"></script>
<script>
var th = jQuery('th'),
li = jQuery('li'),
inverse = false;
th.click(function(){
var header = $(this),
index = header.index();
header
.closest('table')
.find('td')
.filter(function(){
return $(this).index() === index;
})
.sort(function(a, b){
a = $(a).text();
b = $(b).text();
return (
isNaN(a) || isNaN(b) ?
a > b : +a > +b
) ?
inverse ? -1 : 1 :
inverse ? 1 : -1;
}, function(){
return this.parentNode;
});
inverse = !inverse;
});
</script>
</body>
</html>
In the above program when I click on the <th> it sorts the rows in that column. It also uses the .sort method from this file.
Can you explain how the above code works, and its inner working? This is the link where I got the above code:
Explanation in comments inline:
Comaprison (sort) Function:
The comparison function is interesting. To make it more readable consider the following function and example input/output:
Output:
Explanation:
The
isNaNfunction returns true if the input ‘is not a number’ and false otherwise. Conveniently, it considers strings of digits to be numbers. So if we are comparing two numbers (whether strings or not) our comparison function returnsAppending the
+just converts the string to a real javascript numerical object, meaning that the text won’t be alphabetically sorted when the text represents numerical values.If either cell’s contents is not a number, then the comparison function returns
…which just applies the default
>operator for the object. In the case of strings, it will result in sorting the strings alphabetically.