Sort an array in the same order of another array
Use indexOf()
to get the position of each element in the reference array, and use that in your comparison function.
var reference_array = ["ryan", "corbin", "dan", "steven", "bob"];
var array = ["bob", "dan", "steven", "corbin"];
array.sort(function(a, b) {
return reference_array.indexOf(a) - reference_array.indexOf(b);
});
console.log(array); // ["corbin", "dan", "steven", "bob"]
Searching the reference array every time will be inefficient for large arrays. If this is a problem, you can convert it into an object that maps names to positions:
var reference_array = ["ryan", "corbin", "dan", "steven", "bob"];
reference_object = {};
for (var i = 0; i < reference_array.length; i++) {
reference_object[reference_array[i]] = i;
}
var array = ["bob", "dan", "steven", "corbin"];
array.sort(function(a, b) {
return reference_object[a] - reference_object[b];
});
console.log(array);
You can realize some sorter by patter factory function. Then create sorter using your pattern and apply it to your arrays:
function sorterByPattern(pattern) {
var hash = {};
pattern.forEach(function(name, index) { hash[name] = index });
return function(n1, n2) {
if (!(n1 in hash)) return 1; // checks if name is not in the pattern
if (!(n2 in hash)) return -1; // if true - place that names to the end
return hash[n1] - hash[n2];
}
}
var sorter = sorterByPattern(["ryan", "corbin", "dan", "steven", "bob"]);
var arrays = [
["dan", "ryan", "bob", "steven", "corbin"],
["bob", "dan", "steven", "corbin"]
/* ... */
];
arrays.forEach(function(array) { array.sort(sorter) });