Function: maxByKey()
maxByKey<
ElementType
,MappedType
>(iterable
:IterableResolvable
<ElementType
>,callbackFn
: (element
:ElementType
,index
:number
) =>MappedType
,comparator
:CompareByComparator
<MappedType
>):ElementType
|null
Returns the element that gives the maximum value from the specified function.
If several elements are equally maximum, the last element is returned. If the iterator is empty, null
is returned.
Type Parameters
Type Parameter |
---|
ElementType |
MappedType |
Parameters
Parameter | Type | Default value | Description |
---|---|---|---|
iterable | IterableResolvable <ElementType > | undefined | An iterator of number values to determine the maximum value of. |
callbackFn | (element : ElementType , index : number ) => MappedType | undefined | A function to execute for each element produced by the iterator, producing a key to compare with. |
comparator | CompareByComparator <MappedType > | defaultCompare | A function to execute for each element produced by the iterator. It should return a number value. |
Returns
ElementType
| null
The element that gives the maximum value from the specified function, or null
if the iterator is empty.
Seealso
max for a version that uses the default comparator.
Seealso
maxBy for a version that allows custom comparators.
Example
import { maxByKey } from '@sapphire/iterator-utilities';
const iterable = [-3, 0, 1, 5, -10];
console.log(maxByKey(iterable, (value) => Math.abs(value)));
// Output: -10
Remarks
This function consumes the entire iterator.
Defined in
projects/utilities/packages/iterator-utilities/src/lib/maxByKey.ts:35