Skip to content

Instantly share code, notes, and snippets.

@gareth-cheeseman
Last active December 21, 2018 12:53
Show Gist options
  • Save gareth-cheeseman/ce5b263e9ca33fc23461a8400a4f82b3 to your computer and use it in GitHub Desktop.
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.
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