How to use Array.reduce() method In Javascript
TheJavaScript Array.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: we are Using JavaScript Array.reduce() method
// Input array
let Arr = [50, 60, 20, 10, 40];
// Getting min value
let minValue = Arr.reduce((acc, current) => Math.min(acc, current));
// Getting max value
let maxValue = Arr.reduce((acc, current) => Math.max(acc, current));
// Display output
console.log("Minimum element is:" + minValue);
console.log("Minimum element is:" + maxValue);
Output
Minimum element is:10 Minimum element is:60
Find the min/max element of an Array using JavaScript
Finding the minimum or maximum element of an array in JavaScript involves determining the smallest or largest value from the array’s elements. This operation is crucial for various tasks, such as data analysis, optimization problems, and comparisons within algorithms.
The minimum and maximum elements in an array can be found using the following methods:
Table of Content
- Using Math.min() and Math.max() Methods
- Iterating through the Array
- Using JavaScript Array.reduce() method
- Using apply method
- Using spread operator