Created
May 7, 2013 09:07
-
-
Save qborreda/5531303 to your computer and use it in GitHub Desktop.
jQuery Multi array table sortening
http://jsfiddle.net/VAKrE/105/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Click on the table headings to sort the results. | |
<table> | |
<thead id="headings"> | |
<tr> | |
<th id="f_name">First Name</th> | |
<th id="l_name">Last Name</th> | |
<th id="age">Age</th> | |
</tr> | |
</thead> | |
<tbody id="results"> | |
<!-- this will be auto-populated --> | |
</tbody> | |
</table> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
table { | |
margin: 3px; | |
} | |
table th { | |
font-weight: bold; | |
cursor: pointer; | |
} | |
table th, table td { | |
padding: 3px; | |
border: 1px solid #000; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var arr = [ | |
{ | |
f_name: 'George', | |
l_name: 'Washington', | |
age: 279 | |
}, | |
{ | |
f_name: 'Abraham', | |
l_name: 'Lincoln', | |
age: 202 | |
}, | |
{ | |
f_name: 'Barack', | |
l_name: 'Obama', | |
age: 50 | |
} | |
]; | |
$(function() { | |
$('#headings th').click(function() { | |
var id = $(this).attr('id'); | |
var asc = (!$(this).attr('asc')); // switch the order, true if not set | |
// set asc="asc" when sorted in ascending order | |
$('#headings th').each(function() { | |
$(this).removeAttr('asc'); | |
}); | |
if (asc) $(this).attr('asc', 'asc'); | |
sortResults(id, asc); | |
}); | |
showResults(); | |
}); | |
function sortResults(prop, asc) { | |
arr = arr.sort(function(a, b) { | |
if (asc) return (a[prop] > b[prop]); | |
else return (b[prop] > a[prop]); | |
}); | |
showResults(); | |
} | |
function showResults () { | |
var html = ''; | |
for (var e in arr) { | |
html += '<tr>' | |
+'<td>'+arr[e].f_name+'</td>' | |
+'<td>'+arr[e].l_name+'</td>' | |
+'<td>'+arr[e].age+'</td>' | |
+'</tr>'; | |
} | |
$('#results').html(html); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment