.sortBy and .orderBy

Sorts an array of object based on an object key provided by a parameter (note this is more limited than Underscore/Lodash).

  1. const fruits = [
  2. {name:"banana", amount: 2},
  3. {name:"apple", amount: 4},
  4. {name:"pineapple", amount: 2},
  5. {name:"mango", amount: 1}
  6. ];
  7.  
  8. // Underscore
  9. _.sortBy(fruits, 'name');
  10. // => [{name:"apple", amount: 4}, {name:"banana", amount: 2}, {name:"mango", amount: 1}, {name:"pineapple", amount: 2}]
  11.  
  12. // Lodash
  13. _.orderBy(fruits, ['name'],['asc']);
  14. // => [{name:"apple", amount: 4}, {name:"banana", amount: 2}, {name:"mango", amount: 1}, {name:"pineapple", amount: 2}]
  15.  
  16. // Native
  17. const sortBy = (key) => {
  18. return (a, b) => (a[key] > b[key]) ? 1 : ((b[key] > a[key]) ? -1 : 0);
  19. };
  20.  
  21. // The native sort modifies the array in place. `_.orderBy` and `_.sortBy` do not, so we use `.concat()` to
  22. // copy the array, then sort.
  23. fruits.concat().sort(sortBy("name"));
  24. // => [{name:"apple", amount: 4}, {name:"banana", amount: 2}, {name:"mango", amount: 1}, {name:"pineapple", amount: 2}]

Browser Support for Array.prototype.concat() and Array.prototype.sort()

ChromeEdgeFirefoxIEOperaSafari
1.0 ✔1.0 ✔5.5 ✔