Skip to content

Instantly share code, notes, and snippets.

@ricardobeat
Created February 1, 2012 21:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ricardobeat/1719375 to your computer and use it in GitHub Desktop.
Save ricardobeat/1719375 to your computer and use it in GitHub Desktop.
Table sorter
$.fn.sort = (col, order) ->
getText = (c) -> $(c.cells[col]).text()
toNum = (n) -> parseFloat number.replace(/\./g,"").replace(/,/g,".")
@each ->
numbers = /^[-0-9.,]*$/.test($(@rows[0].cells[0]).text())
$(this).html Array::slice.call(@rows, 0).sort (a,b) ->
[a,b] = [b,a] if order is 'desc'
[a,b] = [getText a, getText b]
[a,b] = [toNum a, toNum b] if numbers
return 1 if a > b
return -1 if a < b
return 0
$.fn.sort = function (col, order){
function toNum(number) {
return parseFloat(number.replace(/\./g,"").replace(/,/g,"."))
}
return this.each(function(){
var numbers = /^[-0-9.,]*$/.test($(this.rows[0].cells[0]).text())
var rows = [].slice.call(this.rows, 0).sort(function(a,b){
if (order === 'desc') b = [a,a=b][0]
a = $(a.cells[col]).text()
b = $(b.cells[col]).text()
if (numbers) a = toNum(a), b = toNum(b)
return (a > b) ? 1 : (a < b) ? -1 : 0
})
$(this).html( rows )
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment