Merge pull request #567 from liuliangsir/master

Added getMinOrMaxValueInArrayBySomeRules utility function
This commit is contained in:
Angelos Chalaris
2018-01-25 13:41:12 +02:00
committed by GitHub

16
snippets/reduceWhich.md Normal file
View File

@ -0,0 +1,16 @@
### reduceWhich
Returns the minimum/maximum value of an array, after applying the provided function to set comparing rule.
Use `Array.reduce()` in combination with the `comparator` function to get the appropriate element in the array.
You can omit the second parameter, `comparator`, to use the default one that returns the minimum element in the array.
```js
const reduceWhich = (arr, comparator = (a, b) => a - b) => arr.reduce((a, b) => comparator(a, b) >= 0 ? b : a);
```
```js
reduceWhich([1, 3, 2]); // 1
reduceWhich([1, 3, 2], (a, b) => b - a); // 3
reduceWhich([{name: 'Tom', age: 12}, {name: 'Jack', age: 18}, {name: 'Lucy', age: 9}], (a, b) => a.age - b.age); // {name: "Lucy", age: 9}
```