How to use reduce() Method In Javascript
The Javascript arr.reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of the array (from left to right) and the return value of the function is stored in an accumulator.
Syntax:
array.reduce( function(total, currentValue, currentIndex, arr),
initialValue )
Example:
function LargestElement(arr) {
if (arr.length === 0) {
console.log("Array is empty");
}
return arr.reduce(function (a, b) {
return (a > b) ? a : b});
}
const arr = [22, 65, 1, 39];
console.log("Largest in given array is " + LargestElement(arr));
Output
Largest in given array is 65
Javascript Program to Find the Largest Element in an Array
Finding the largest element in an array is a common task in JavaScript, useful in various scenarios such as data analysis, sorting, and mathematical computations. This article explores several methods to efficiently determine the largest element, ensuring robust and optimized solutions for your coding needs. Let’s first see simple examples input and output.
Examples:
Input: arr = [10, 20, 4]
Output: 20
Explanation: Among 10, 20 and 4, 20 is the largest.Input : arr = [20, 10, 20, 4, 100]
Output : 100