Created
August 20, 2017 16:26
-
-
Save beatak/42c21b6439f7a1a6aa3e7094e96d349c to your computer and use it in GitHub Desktop.
just sorting
This file contains hidden or 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 tablesorter = function(table) { | |
var data = [], | |
header = {}, | |
header_tr, | |
$table = $(table), | |
is_asc = false, | |
$indicator = $('<span></span>'); | |
$table.find('th').each(function(i, th) { | |
var $th = $(th); | |
header[i] = $th.text().trim(); | |
header_tr = th.parentNode; | |
$th.attr('myindex', i); // data will be destroyed after modification | |
// console.log(i + ': ' + header[i]); | |
}); | |
$table.find('tr').each(function (i, tr) { | |
if (tr === header_tr) { | |
return; | |
} | |
var obj = {}; | |
$(tr).find('td').each(function (_i, td) { | |
obj[_i] = $(td).text().trim(); | |
obj.tr = td.parentNode; | |
}); | |
data.push(obj); | |
}); | |
$table.on('click', 'th', function (ev) { | |
var $th = $(ev.currentTarget); | |
var idx = $th.attr('myindex'); | |
// console.log('sorting: ' + data.length + ' by ' + header[idx] + '(' + idx + ')'); | |
if ($indicator[0].parentNode === $th[0]) { | |
is_asc = !is_asc; | |
} else { | |
is_asc = false; | |
$th.append($indicator); | |
} | |
if (is_asc) { | |
$indicator.text('↑'); | |
} else { | |
$indicator.text('↓'); | |
} | |
data.sort(function (a, b) { | |
var a_val = a[idx]; | |
var b_val = b[idx]; | |
var a_num_val = parseFloat(a_val); | |
var b_num_val = parseFloat(b_val); | |
if (!isNaN(a_num_val) && !isNaN(b_num_val)) { | |
if (a_num_val === b_num_val) { | |
return 0; | |
} | |
else if (a_num_val < b_num_val) { | |
return is_asc ? -1 : 1; | |
} | |
else { | |
return is_asc ? 1 : -1; | |
} | |
} | |
else { | |
if (a_val < b_val) { | |
return is_asc ? -1 : 1; | |
} else if (a_val > b_val) { | |
return is_asc ? 1 : -1; | |
} | |
else { | |
return 0; | |
} | |
} | |
}); | |
$table.empty(); | |
$table.append(header_tr); | |
data.forEach(function (obj) { | |
$table.append(obj.tr); | |
}); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment