Skip to main content

Function: maxBy()

maxBy<ElementType>(iterable: IterableResolvable<ElementType>, comparator: CompareByComparator<ElementType>): null | ElementType

Defined in: projects/utilities/packages/iterator-utilities/src/lib/maxBy.ts:33

Returns the element that gives the maximum value with respect to the specified comparison 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

Parameters​

ParameterTypeDescription
iterableIterableResolvable<ElementType>An iterator of number values to determine the maximum value of.
comparatorCompareByComparator<ElementType>A function to execute for each element produced by the iterator. It should return a number value.

Returns​

null | ElementType

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​

maxByKey for a version that allows custom key extractors.

Example​

import { ascNumber, maxBy } from '@sapphire/iterator-utilities';

const iterable = [-3, 0, 1, 5, -10];
console.log(maxBy(iterable, ascNumber));
// Output: 5

Remarks​

This function consumes the entire iterator.