Skip to content

Instantly share code, notes, and snippets.

@tjunghans
Last active August 29, 2015 14:27
Show Gist options
  • Save tjunghans/79cb4f1c23c6f9df9c2d to your computer and use it in GitHub Desktop.
Save tjunghans/79cb4f1c23c6f9df9c2d to your computer and use it in GitHub Desktop.
Sort array according to array
// It is expected that `order` and `items` have the same length
// and that all key values in items exist in order
// Order according to
var order = [ 'charlie', 'delta', 'quebec', 'foxtrott' ];
// Needs re-ordering
var items = [
{ key: 'charlie' },
{ key: 'delta' },
{ key: 'foxtrott' }, // not in order
{ key: 'quebec'}
];
function itemFilter(item) {
return item.key;
}
function sortArrayByArray(items, order, itemFilter) {
var sorted = [];
items.forEach(function (item) {
var pos = order.indexOf(itemFilter ? itemFilter(item) : item);
if (pos > -1) {
sorted[pos] = item;
}
});
return sorted;
}
console.log(sortArrayByArray(items, order, itemFilter));
// expect: [{ key: 'charlie' }, { key: 'delta' }, { key: 'quebec'}, { key: 'foxtrott' }]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment