How to use the reduce() Method In Javascript
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.
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));
Output
38
JavaScript Program to Find Largest Element in an Array
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.
Several methods can be used to find the largest Element in an Array in Javascript, which are listed below:
Table of Content
- Using the reduce() Method
- Using the Spread Operator and Math.max() Method
- Using for Loop
- Using the sort() method
- Using a ForEach Loop