-
-
Save victorpavlov/83150f9b8d0aa3af8e6d067cad0095ce to your computer and use it in GitHub Desktop.
Order an array of objects based on another array order
This file contains 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
/** | |
* Sort array of objects based on another array | |
*/ | |
const mapOrder = (array, order, key) => { | |
array.sort((a, b) => { | |
const A = a[key]; | |
const B = b[key]; | |
return order.indexOf(A) > order.indexOf(B) ? 1 : -1; | |
}); | |
return array; | |
}; | |
/** | |
* Example: | |
*/ | |
var item_array, item_order, ordered_array; | |
item_array = [ | |
{ id: 2, label: 'Two' } | |
, { id: 3, label: 'Three' } | |
, { id: 5, label: 'Five' } | |
, { id: 4, label: 'Four' } | |
, { id: 1, label: 'One'} | |
]; | |
item_order = [1,2,3,4,5]; | |
ordered_array = mapOrder(item_array, item_order, 'id'); | |
console.log('Ordered:', JSON.stringify(ordered_array)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment