String/Numeric Comparison
HTML
<div class="output1">Numeric array: </div>
<div class="output2">After sort: </div>
<div class="output3">String array: </div>
<div class="output4">After sort: </div>
JavaScript
// Sorting order
var order = "asc"; // Try switching between "asc" and "dsc"
// Dummy arrays
var numericArr = [10,20,null,1,-2,-3,null,5];
var stringArr = [10,"20",null,"1","0bar","-2",-3,null,5,"2foo"];
// Sort arrays
$(".output1").append(numericArr.toString());
numericArr.sort(sortByDataNumeric);
$(".output2").append(numericArr.toString());
$(".output3").append(stringArr.toString());
stringArr.sort(sortByDataString);
$(".output4").append(stringArr.toString());
// Numeric sorting function
function sortByDataNumeric(a, b, _order) {
// Replace internal parameters if not used
if (_order == null) _order = order;
// If values are null, place them at the end
var dflt = (_order == "asc" ? Number.MAX_VALUE : -Number.MAX_VALUE);
// Numeric values
var aVal = (a == null ? dflt : a);
var bVal = (b == null ? dflt : b);
return _order == "asc" ? (aVal - bVal) : (bVal - aVal);
}
// String sorting function
function sortByDataString(a, b, _order) {
// Replace internal parameters if not used
if (_order == null) _order = order;
// If values are null, place them at the end
var dflt = (_order == "asc" ? Number.MAX_VALUE : -Number.MAX_VALUE);
//String values
var aVal = (a == null ? dflt : a).toString();
var bVal = (b == null ? dflt : b).toString();
return _order == "asc" ? aVal.localeCompare(bVal, undefined, {numeric: true}) : bVal.localeCompare(aVal, undefined, {numeric: true});
}