In this article, we are going to learn about the largest element in an array in JavaScript. The largest element in an array refers to the value that holds the greatest numerical or lexicographic (string) order among all elements present in the array.
Example:
Input : [10, 15, 38, 20, 13];
Output: 38
Here we will see the 38 is the largest elements in the given array.
There are several methods that can be used to find the largest Element in an Array in Javascript, which are listed below:
- Using reduce() method
- Using the Spread Operator and Math.max() Method
- Using for Loop
We will explore all the above methods along with their basic implementation with the help of examples.
JavaScript Program to Find Largest Element in an Array using the reduce() Method
In this approach, Using the reduce() method, iterate through the array while comparing elements. Accumulate the largest element by updating the accumulator if the current element is greater. Return the largest element.
Syntax:
array.reduce( function(total, currentValue, currentIndex, arr), initialValue )
Example: In this approach, we are using the above-explained approach.
Javascript
function largestElement(arr) { return arr.reduce((largest, current) => (current > largest ? current : largest), arr[0]); } let num1 = [10, 15, 38, 20, 13]; console.log(largestElement(num1)); |
38
JavaScript Program to Find Largest Element in an Array using the Spread Operator and Math.max() Method
In this approach, the spread operator (…) with Math.max(), directly pass array elements as arguments, allowing the method to find and return the largest element in the array.
Syntax:
function largestElement(arr) {
return Math.max(...arr);
};
Example: In this example, we are using the Spread Operator and Math.max() to find the largest number from our given array.
Javascript
function largestElement(arr) { return Math.max(...arr); } const num1 = [10, 15, 28, 20, 13]; const result = largestElement(num1); console.log( "The largest element in the array is:" + result); |
The largest element in the array is:28
JavaScript Program to Find Largest Element in an Array using for Loop
In this approach, Using a for loop, iterate through the array, comparing each element to a running largest value, updating it if a larger element is encountered, and returning the final largest value.
Syntax:
for (let i = 1; i < arr.length; i++) {
if (arr[i] > largestNum) {
largestNum = arr[i];
}
};
Example: In this approach, we are using for loop to find the largest number from our given array.
Javascript
function largestElement(arr) { let largestNum = arr[0]; for (let i = 1; i < arr.length; i++) { if (arr[i] > largestNum) { largestNum = arr[i]; } } return largestNum; } const num1 = [10, 15, 18, 20, 23]; const result = largestElement(num1); console.log( "The largest element in the array is:" + result); |
The largest element in the array is:23