Overview
Implement maxBy(array, iteratee) — returns element with largest iteratee value.
Examples
maxBy([{n:1},{n:2}], o => o.n); // {n:2}Solution
Reveal solution
function maxBy(array, iteratee) {
if (!array.length) return undefined;
let max = array[0], maxV = iteratee(array[0]);
for (let i = 1; i < array.length; i++) {
const v = iteratee(array[i]);
if (v > maxV) { maxV = v; max = array[i]; }
}
return max;
}max-by.js
Max By
easycodingJavaScriptArrays
Overview
Implement maxBy(array, iteratee) — returns element with largest iteratee value.
Examples
maxBy([{n:1},{n:2}], o => o.n); // {n:2}Solution
Reveal solution
function maxBy(array, iteratee) {
if (!array.length) return undefined;
let max = array[0], maxV = iteratee(array[0]);
for (let i = 1; i < array.length; i++) {
const v = iteratee(array[i]);
if (v > maxV) { maxV = v; max = array[i]; }
}
return max;
}NameTopicDifficulty
103 of 103 problems