Find the maximum item of an array by given key
Return the record with the largest value in a field.
function maxBy({ values, key }) { return values.reduce((best, item) => (best === null || item[key] > best[key] ? item : best), null); }
Input & expected output
Input
{
"values": [
{
"recipient": "[email protected]",
"attempts": 1
},
{
"recipient": "[email protected]",
"attempts": 3
}
],
"key": "attempts"
}Expected output
{
"recipient": "[email protected]",
"attempts": 3
}The edge case
Input
{
"values": [],
"key": "attempts"
}Expected output
nullKnow the limits
- An empty array returns null; the original returned {}.
- The first record wins on ties.
The function above is the implementation used by the lab. The lab validates JSON types and caps size before execution; include equivalent validation when accepting untrusted input in your application.
Source & maintenance
Based on Find the maximum item of an array by given key from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Returns null for an empty array instead of an empty object. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Clone an array — Create a new array without copying the objects inside it.
- Remove duplicate values — Keep the first occurrence of each value, in its original order.
- Flatten a nested array — Turn a nested array into one sequence of values.