Find min and max elements by criterion in a single pass
A flight search page highlights the cheapest and the most expensive result, and a leaderboard shows the slowest and fastest lap. Both need the element with the smallest and the largest value of some criterion, found in one pass. Computing the criterion can be expensive (it may parse a string or convert a currency), so it must run only once per element.
Implement extremesBy(array, iteratee).
extremesBy(array, iteratee) // => { min, max, minIndex, maxIndex }
iteratee is either a function called as iteratee(value, index), or a string key. A key means the criterion is value[key], or undefined when value is null or undefined.null, undefined, or NaN.min / max are the elements (not the criteria) with the smallest and largest criterion. minIndex / maxIndex are their indexes.< and >.{ min: undefined, max: undefined, minIndex: -1, maxIndex: -1 }.const flights = [
{ code: 'LX318', price: 212 },
{ code: 'BA729', price: 189 },
{ code: 'KL1002', price: null },
{ code: 'AF1681', price: 344 },
{ code: 'U28501', price: 189 },
];
extremesBy(flights, 'price');
// => {
// min: { code: 'BA729', price: 189 }, (first of the two 189s)
// max: { code: 'AF1681', price: 344 },
// minIndex: 1,
// maxIndex: 3,
// }
extremesBy(['1:42.7', '1:39.9', '1:44.1'], (lap) => {
const [minutes, seconds] = lap.split(':');
return Number(minutes) * 60 + Number(seconds);
});
// => { min: '1:39.9', max: '1:44.1', minIndex: 1, maxIndex: 2 }
extremesBy(['pear', 'fig', 'banana'], (word) => word);
// => { min: 'banana', max: 'pear', minIndex: 2, maxIndex: 0 }
extremesBy([{ price: null }], 'price');
// => { min: undefined, max: undefined, minIndex: -1, maxIndex: -1 }