Created
June 14, 2019 04:02
-
-
Save kukiron/85d4fc087b82fd2416be9f6fd5c2fa02 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
const mapOrder = (array, order, key) => array | |
.sort((a, b) => order.indexOf(a[key]) > order.indexOf(b[key]) ? 1 : -1); | |
/** | |
* Example: | |
*/ | |
const item_array = [ | |
{ id: 2, label: 'Two' }, | |
{ id: 3, label: 'Three' }, | |
{ id: 5, label: 'Five' }, | |
{ id: 4, label: 'Four' }, | |
{ id: 1, label: 'One'}, | |
]; | |
const item_order = [1,2,3,4,5]; | |
const ordered_array = mapOrder(item_array, item_order, 'id'); | |
console.log('Ordered:', ordered_array); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment