The same basic idea as Guffa's solution, but with a reusable API:
var makeSorter = function(pattern) {
var map = _.mapValues(_.invert(pattern), Number);
return function(vals) {
return vals.sort(function(a, b) {
return map[a] - map[b];
});
};
};
var mySorter = makeSorter(['D', 'C', 'A', 'B']);
mySorter(['A', 'B', 'C', 'D']); //=> ["D", "C", "A", "B"]
mySorter(['A', 'C', 'D']); //=> ["D", "C", "A"]
If there might be values in your data not in your pattern, then you might need something slightly more complex:
var makeSorter = function(pattern) {
var map = _.mapValues(_.invert(pattern), function(s) {return Number(s) + 1;});
return function(vals) {
return vals.sort(function(a, b) {
return (map[a] || Infinity) - (map[b] || Infinity);
});
};
};
mySorter(['A', 'X', 'B', 'C', 'Q']); //=> ["C", "A", "B", "X", "Q"]
Also, how nice ES6 arrow functions are. This is the equivalent of the first version, in ES6:
var makeSorter = pattern => {
let map = _.mapValues(_.invert(pattern), Number);
return vals => vals.sort((a, b) => map[a] - map[b]);
};