.minBy and .maxBy
Use Array#reduce for find the maximum or minimum collection item
- // Underscore/Lodash
- var data = [{ value: 6 }, { value: 2 }, { value: 4 }]
- var minItem = _.minBy(data, 'value')
- var maxItem = _.maxBy(data, 'value')
- console.log(minItem, maxItem)
- // output: { value: 2 } { value: 6 }
- // Native
- var data = [{ value: 6 }, { value: 2 }, { value: 4 }]
- var minItem = data.reduce(function(a, b) { return a.value <= b.value ? a : b }, {})
- var maxItem = data.reduce(function(a, b) { return a.value >= b.value ? a : b }, {})
- console.log(minItem, maxItem)
- // output: { value: 2 }, { value: 6 }
Extract a functor and use es2015 for better code
- // utils
- const makeSelect = (comparator) => (a, b) => comparator(a, b) ? a : b
- const minByValue = makeSelect((a, b) => a.value <= b.value)
- const maxByValue = makeSelect((a, b) => a.value >= b.value)
- // main logic
- const data = [{ value: 6 }, { value: 2 }, { value: 4 }]
- const minItem = data.reduce(minByValue, {})
- const maxItem = data.reduce(maxByValue, {})
- console.log(minItem, maxItem)
- // output: { value: 2 }, { value: 6 }
- // or also more universal and little slower variant of minBy
- const minBy = (collection, key) => {
- // slower because need to create a lambda function for each call...
- const select = (a, b) => a[key] <= b[key] ? a : b
- return collection.reduce(select, {})
- }
- console.log(minBy(data, 'value'))
- // output: { value: 2 }
Browser Support for Array.prototype.reduce()
✔ | ✔ | 3.0 ✔ | 9.0 ✔ | 10.5 ✔ | 4.0 ✔ |
当前内容版权归 you-dont-need 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 you-dont-need .