Skip to main content

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

ParameterTypeDefault valueDescription
iterableIterableResolvable<ElementType>undefinedAn iterator of number values to determine the maximum value of.
callbackFn(element: ElementType, index: number) => MappedTypeundefinedA function to execute for each element produced by the iterator, producing a key to compare with.
comparatorCompareByComparator<MappedType>defaultCompareA 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