.minBy and .maxBy

Use Array#reduce for find the maximum or minimum collection item

  1. // Underscore/Lodash
  2. var data = [{ value: 6 }, { value: 2 }, { value: 4 }]
  3. var minItem = _.minBy(data, 'value')
  4. var maxItem = _.maxBy(data, 'value')
  5. console.log(minItem, maxItem)
  6. // output: { value: 2 } { value: 6 }
  7.  
  8. // Native
  9. var data = [{ value: 6 }, { value: 2 }, { value: 4 }]
  10. var minItem = data.reduce(function(a, b) { return a.value <= b.value ? a : b }, {})
  11. var maxItem = data.reduce(function(a, b) { return a.value >= b.value ? a : b }, {})
  12. console.log(minItem, maxItem)
  13. // output: { value: 2 }, { value: 6 }

Extract a functor and use es2015 for better code

  1. // utils
  2. const makeSelect = (comparator) => (a, b) => comparator(a, b) ? a : b
  3. const minByValue = makeSelect((a, b) => a.value <= b.value)
  4. const maxByValue = makeSelect((a, b) => a.value >= b.value)
  5.  
  6. // main logic
  7. const data = [{ value: 6 }, { value: 2 }, { value: 4 }]
  8. const minItem = data.reduce(minByValue, {})
  9. const maxItem = data.reduce(maxByValue, {})
  10.  
  11. console.log(minItem, maxItem)
  12. // output: { value: 2 }, { value: 6 }
  13.  
  14. // or also more universal and little slower variant of minBy
  15. const minBy = (collection, key) => {
  16. // slower because need to create a lambda function for each call...
  17. const select = (a, b) => a[key] <= b[key] ? a : b
  18. return collection.reduce(select, {})
  19. }
  20.  
  21. console.log(minBy(data, 'value'))
  22. // output: { value: 2 }

Browser Support for Array.prototype.reduce()

ChromeEdgeFirefoxIEOperaSafari
3.0 ✔9.0 ✔10.5 ✔4.0 ✔