Guest User

Untitled

a guest
May 22nd, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.01 KB | None | 0 0
  1. const sampleArray = [
  2. {
  3. numProp: 5,
  4. alphaProp: 'Foo',
  5. charProp: 'e'
  6. },
  7. {
  8. numProp: 4,
  9. alphaProp: 'Bar',
  10. charProp: 'a'
  11. },
  12. {
  13. numProp: 7,
  14. alphaProp: 'Baz',
  15. charProp: 'd'
  16. },
  17. {
  18. numProp: 9,
  19. alphaProp: 'Qux',
  20. charProp: 'g'
  21. }
  22. ];
  23.  
  24. const numericSort = prop => ({[prop]: a}, {[prop]: b}) => a - b;
  25.  
  26. const alphaSort = prop => ({[prop]: a}, {[prop]: b}) => a < b ? -1 : 1;
  27.  
  28. const weirdCustomSort = prop => ({[prop]: a}, {[prop]: b}) => {
  29. const elements = ['a','e','b','d','c'];
  30. const aIndex = ~elements.indexOf(a) ? elements.indexOf(a) : elements.length;
  31. const bIndex = ~elements.indexOf(b) ? elements.indexOf(b) : elements.length;
  32. return aIndex - bIndex;
  33. };
  34.  
  35.  
  36.  
  37. const compareBy = prop => sortFunc => sortFunc(prop);
  38.  
  39. const numSortedArray = [...sampleArray].sort(compareBy('numProp')(numericSort));
  40. const alphaSortedArray = [...sampleArray].sort(compareBy('alphaProp')(alphaSort));
  41. const customSortedArray = [...sampleArray].sort(compareBy('charProp')(weirdCustomSort));
Add Comment
Please, Sign In to add comment