碎片時(shí)間學(xué)編程「130]:基于提供的函數(shù)數(shù)組返回最小值和最大值

在應(yīng)用提供的函數(shù)設(shè)置比較規(guī)則后,返回?cái)?shù)組的最小值/最大值。
Array.prototype.reduce()與函數(shù) comparator 結(jié)合使用以獲取數(shù)組中的適當(dāng)元素。
省略第二個(gè)參數(shù) comparator以使用返回?cái)?shù)組中最小元素的默認(rèn)參數(shù)。
JavaScript
const reduceWhich = (arr, comparator = (a, b) => a - b) =>
?arr.reduce((a, b) => (comparator(a, b) >= 0 ? b : a));
示例:
reduceWhich([1, 3, 2]); // 1reduceWhich([1, 3, 2], (a, b) => b - a); // 3reduceWhich( ?[ ? ?{ name: 'Tom', age: 12 }, ? ?{ name: 'Jack', age: 18 }, ? ?{ name: 'Lucy', age: 9 } ?], ?(a, b) => a.age - b.age); // {name: 'Lucy', age: 9}
更多內(nèi)容請(qǐng)?jiān)L問(wèn)我的網(wǎng)站:https://www.icoderoad.com
標(biāo)簽: