Get the largest value from an array using javascript
In this post, we will learn different methods and functions to get the largest value from an array. We will use Math.max() function in order to do that along with other methods with explanation.
Get the largest value from an array using javascript
To get the largest value from an array:
- Create an array eg. - arr = [50, 20, 60, 90, 30, 70].
- Use Math.max() function to get the largest value from the array. eg. Math.max(...arr).
Using Math.max() function
The Math.max() function in JavaScript is used to return the largest value from a given array of numbers. It takes an array of numbers as an argument and returns the number with the highest value in the array.
It is a built-in function used to find the largest number in the array. It is a very useful and convenient tool for quickly determining the largest value from an array of numbers. This function can be used to quickly and easily find the maximum value for a given array of numbers.
We will also use the spread operator in Math.max() function.
Syntax
Math.max(...array)
const arr = [50, 20, 60, 90, 30, 70];
const max_val = Math.max(...arr);
console.log(max_val);
Output
90
This code snippet declares a constant array and assigns it some values. It then declares a constant called max_val and assigns it the value of the highest number in the array using the Math.max() method with the spread operator. Finally, it prints the value of max_val to the console.
Using for loop
function largest_val(arr) {
let max = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
const max_val = largest_val([50, 20, 60, 90, 30, 70]);
console.log(max_val);
Output
90
- Javascript Code for Sorting array and finding Largest No. in Array
- Find the nth largest element in a sorted array
- Convert object {key: value} to Array [[key, value]] Javascript
- Find the maximum value from an array using Javascript
- Find the index of Max value in an array using Javascript
- Filter an Array using object key value in Javascript
- Lodash - Get index of first occurence of an array value