Jump to the editorJAVASCRIPT
JAVASCRIPT JAVASCRIPT
4.6. Max, min and mean by a key
Easy
Topics
This question is in
4. Array utilitiesA leaderboard shows the player with the highest score. A flight search highlights the cheapest flight. A dashboard shows the average response time of a list of requests. In each case the array holds objects, and the question is about one field of them: which object has the largest field, which the smallest, and what the field's average is.
Write maxBy(array, iteratee), minBy(array, iteratee) and meanBy(array, iteratee) in byKey.js.
Signature
function maxBy(array, iteratee) // returns an item of array, or undefined
function minBy(array, iteratee) // returns an item of array, or undefined
function meanBy(array, iteratee) // returns a numberiterateegives each item's key: either a function, called asiteratee(item), or a property name such as"score", which meansitem.score.maxByandminByreturn the item itself, not its key.
Requirements
maxByreturns the item with the largest key;minBythe item with the smallest.iterateecan be a function or a property name.- When several items share the largest (or smallest) key, the first of them is returned.
- Negative keys and a key of
0work like any other number. - Items whose key is
undefined,nullorNaNare skipped. An empty array, or one where every key is skipped, givesundefined. - Keys are compared with
>and<, so strings and dates work too. iterateeis called exactly once per item, with the item.- The input array is not changed.
maxByandminBywork on 300,000 items.meanByreturns the average of every item's key; for an empty array it returnsNaN.
Examples
const players = [{ name: "Ana", score: 40 }, { name: "Raj", score: 72 }, { name: "Li", score: 72 }];
maxBy(players, "score"); // { name: "Raj", score: 72 }: the first 72
minBy(players, (player) => player.score); // { name: "Ana", score: 40 }
meanBy(players, "score"); // 61.333…minBy([{ t: 3 }, { t: null }, { t: -1 }], "t"); // { t: -1 }: null is skipped
maxBy([], "t"); // undefined
meanBy([], "t"); // NaNEnvironment
- Plain JavaScript in a browser page; the tests call the globals
maxBy,minByandmeanByfrombyKey.js. - Arrays have no holes, and every item is an object (or a value the iteratee function accepts). For
meanBy, every key is a number. - Any built-in may be used, but
Math.max(...keys)fails on very large arrays: a call can only take so many arguments.
Hints
- What should the "best so far" be before you have seen any item? Is
0a safe start? - A property name and a function can both be turned into one kind of thing before the loop. Which?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it
Back to the question
Loading the editor…