📈 Returns the maximum value in an array.

Info

If duplicate maximum values are present, the first occurrence is returned.

Syntax

TypeScript
import { max } from '@opentf/std';

max<T>(
  arr: T[] = [],
  by: (val: T) => number | string = (x: T) => x as unknown as number | string
): T | null

Parameters

  • arr: The source array.

  • by: An optional function to extract the numeric or string value for comparison. Defaults to identity function.

Returns

The maximum value or null if the array is empty (after compacting).

Examples

TypeScript
max([]) //=> null

max([1, undefined, 2, null, 3]) //=> 3

max([1, 2, -3, 4, 5]) //=> 5

max(['a', 'b', 'c']) //=> 'c'

max(['apple', 'mango', 'grapes']) //=> 'mango'

const arr = [
  {
    name: 'x',
    age: 10,
  },
  {
    name: 'y',
    age: 16,
  },
  {
    name: 'z',
    age: 13,
  },
  { name: 'y2', age: 16 },
];
max(arr, (f) => f.age)
//=> 
// {
//  name: 'y',
//  age: 16,
// }
Last updated on
Edit this page