String/Numeric Comparison
by Luis Lebolo
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 = "dsc"; // Try switching between "asc" and "dsc"
// Dummy arrays
var numericArr = [10, 20, null, 1, -2, -3, null, 5];
var stringArr = ["dude", 9];
// Sort arrays
/*$(".output1").append(numericArr.toString());
numericArr.sort(function (a, b) {
return sortByData(a, b, undefined, undefined, order)
});
$(".output2").append(numericArr.toString());
*/
$(".output3").append(stringArr.toString());
stringArr.sort(function (a, b) {
return sortByData(a, b, undefined, undefined, order)
});
$(".output4").append(stringArr.toString());
function sortByData(a, b, idx, mapping, order) {
var aVal = a.toString(); // FIXME: mapping
var bVal = b.toString(); // FIXME: mapping
var asc = order.toLowerCase() == "asc";
//console.debug("{0}:{1}, {2}:{3}, {4}".format(a.nm, aVal, b.nm, bVal, aVal - bVal));
// If values are null, place them at the end
if (aVal === null && bVal !== null) return 1;
if (aVal !== null && bVal === null) return -1;
var result = aVal - bVal;
if (isNaN(result)) {
var opt = {
numeric: true
};
return asc ? a.localeCompare(b, undefined, opt) : b.localeCompare(a, undefined, opt);
} else {
return asc ? result : -result;
}
/*// Sort by values of next row (or name if no further sorting)
if (aVal == bVal) {
// NOTE: Incrementing the idx value
var nextRow = hmProperties.rowsToSortBy[++idx];
// If there's no more rows to sort by, just compare by name
if (nextRow == null) {
return compareAxisNames(a,b,true);
}
// Retrieve data for next recursive call
mapping = pub.getHeatmapRowData(nextRow);
order = nextRow.split(naming.DELIM)[naming.ORDER_IDX];
// Recursively multisort
return sortByData(a, b, idx, mapping, order);
}
// Otherwise sort numerically (by order)
return order.toLowerCase() == "asc" ? (aVal - bVal) : (bVal - aVal);*/
}