Last active
January 31, 2018 09:17
-
-
Save kutyel/4216a61c1cf01325095f7abd7aa5e899 to your computer and use it in GitHub Desktop.
Sort an array of objects based on another ordered array of objects 🤓
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
| const copySort = (array, order, key) => | |
| [...array].sort( | |
| (a, b) => order.findIndex(x => x[key] === a[key]) - order.findIndex(x => x[key] === b[key]) | |
| ) | |
| const order = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }] | |
| const unordered = [ | |
| { id: 2, label: 'Two' }, | |
| { id: 3, label: 'Three' }, | |
| { id: 5, label: 'Five' }, | |
| { id: 4, label: 'Four' }, | |
| { id: 1, label: 'One' }, | |
| ] | |
| console.log(copySort(unordered, order, 'id')) | |
| // > [ { id: 1, label: 'One' }, | |
| // > { id: 2, label: 'Two' }, | |
| // > { id: 3, label: 'Three' }, | |
| // > { id: 4, label: 'Four' }, | |
| // > { id: 5, label: 'Five' } ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment