Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const sampleArray = [
- {
- numProp: 5,
- alphaProp: 'Foo',
- charProp: 'e'
- },
- {
- numProp: 4,
- alphaProp: 'Bar',
- charProp: 'a'
- },
- {
- numProp: 7,
- alphaProp: 'Baz',
- charProp: 'd'
- },
- {
- numProp: 9,
- alphaProp: 'Qux',
- charProp: 'g'
- }
- ];
- const numericSort = prop => ({[prop]: a}, {[prop]: b}) => a - b;
- const alphaSort = prop => ({[prop]: a}, {[prop]: b}) => a < b ? -1 : 1;
- const weirdCustomSort = prop => ({[prop]: a}, {[prop]: b}) => {
- const elements = ['a','e','b','d','c'];
- const aIndex = ~elements.indexOf(a) ? elements.indexOf(a) : elements.length;
- const bIndex = ~elements.indexOf(b) ? elements.indexOf(b) : elements.length;
- return aIndex - bIndex;
- };
- const compareBy = prop => sortFunc => sortFunc(prop);
- const numSortedArray = [...sampleArray].sort(compareBy('numProp')(numericSort));
- const alphaSortedArray = [...sampleArray].sort(compareBy('alphaProp')(alphaSort));
- const customSortedArray = [...sampleArray].sort(compareBy('charProp')(weirdCustomSort));
Add Comment
Please, Sign In to add comment