Javascript map-sort
I’m sure sorting method has a real name, but I’ve had no luck searching for it.
function mapSort(array, mapFunction, sortFunction)
{
// Store both original value, and transformed value
var mapData = array.map(function(e)
{
return [e, mapFunction(e)];
});
// Sort the data using the second element of each array item (the mapped one)
var sortedData = mapData.sort(function(a, b)
{
return sortFunction(a[1], b[1]);
});
// Remove the extra transformed value from the sorted array
return sortedData.map(function(e)
{
return e[0];
});
}
// Example
var data = ["a", "b", "A", "B", "C", "c"];
var cmp = function(a, b) { return a > b; };
var map = function(ch) { return ch.toLowerCase(); };
print("Normal: " + data.sort(cmp));
print("Map Sort: " + mapSort(data, map, cmp));
// Normal: A,B,C,a,b,c
// Map Sort: a,A,B,b,c,C