Last active
December 21, 2018 12:53
-
-
Save gareth-cheeseman/ce5b263e9ca33fc23461a8400a4f82b3 to your computer and use it in GitHub Desktop.
Javascript Array.prototype property custom sort of object by property in order of values in array, and normal function to do the same.
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
| Object.defineProperty(Array.prototype, 'sortByOrder', { | |
| value: function(property, valuesInOrder) { | |
| const map = new Map( | |
| valuesInOrder.map(value => [value, valuesInOrder.indexOf(value)]) | |
| ); | |
| return this.sort((a, b) => { | |
| return map.get(a[property]) - map.get(b[property]); | |
| }); | |
| } | |
| }); | |
| const sortByOrder = (array, property, valuesInOrder) => { | |
| const map = new Map( | |
| valuesInOrder.map(value => [value, valuesInOrder.indexOf(value)]) | |
| ); | |
| return array.sort((a, b) => { | |
| return map.get(a[property]) - map.get(b[property]); | |
| }); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment