Last active
August 29, 2015 14:27
-
-
Save tjunghans/79cb4f1c23c6f9df9c2d to your computer and use it in GitHub Desktop.
Sort array according to array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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