Oreol Noumodong

Oreol Noumodong

Tech Lover

How to find the largest number in an array in javascript

18 Jul, 2022 - 01:20 AM

When it comes to finding the largest element in an array, one way that usually comes to mind is to sort the elements in ascending order. After sorting, the first element will represent the smallest element, the next element will be the second smallest, and so on, and the last element will be the largest element of the array.
With this solution, the code will take longer to execute and we will say that our code is not optimized.

The most optimized method is to use a max() method from the static object Math which is a built-in object in javascript that has properties and methods for mathematical constants and functions.

For example:
const arr = [1, 5, 16, 9, -98, 23, -12, 892, 2, -23]; 
         
console.log(Math.max(...arr));
//output: 892

Let's work together!

I am available for new remote opportunities or to be your mentor.

Build with Next.js, Tailwindcss, Express.js and Vercel