Hello Friends 👋,

Welcome To Infinitbility! ❤️

Today, we will learn and see how to find max value in array or in array of objects. here we will use Math max function to get array max value element.

Let’s start today’s tutorial How to find maximum value in array in typescript?


Create Array in typescript

Before going to how to use Math.max() method to get max value let create some example array of numbers and objects.

To create array of numbers we have to write Array<numbers> before creating, like following example.

// To make array of numbers in typescript
let ages: Array<number> = [23,46, 36, 96, 3, 30];

To create array of objects we have to create interface of object before creating, like following example.

// To make array of objects in typescript
interface User {
  id: number;
  name: string;
  age: number;
}

let users: Array<User> = [
  { id: 1, name: 'infinitbility', age: 2 },
  { id: 2, name: 'notebility', age: 6 },
  { id: 3, name: 'repairbility', age: 10 },
];

Find max value in array

We have to send array element in Math.max() method and it will return highest number from passed arrays element.

Note: here i’m saying send array of elements not array

we have to pass all our element like this Math.max(2, 6, 7, 20); and then it will return 20.

// Find largest number from array of numbers
let ages: Array<number> = [23,46, 36, 96, 3, 30];
Math.max(...ages);

// ind largest number from array of objects
interface User {
  id: number;
  name: string;
  age: number;
}

let users: Array<User> = [
  { id: 1, name: 'infinitbility', age: 2 },
  { id: 2, name: 'notebility', age: 6 },
  { id: 3, name: 'repairbility', age: 10 },
];
Math.max(...users.map(function(user: User) { return user.age; }));

Output

TypeScript find max Example
TypeScript, find max Example

Thanks for reading…