How to use apply method In Javascript
Using apply( ) method we can invoke a given function with different objects.
Syntax:
object.objectMethod.apply(objectInstance, arrayOfArguments)
Parameters:
- ObjectInstance: It is an object which we want to use explicitly
- Arguments: It is arguments that we want to pass to the calling function
Example: We are using apply method.
// Sample array
const numbers = [5, 2, 8, 1, 4];
// Using apply method to find the minimum element
const minElement = Math.min.apply(null, numbers);
console.log('Minimum Element:', minElement);
// Using apply method to find the maximum element
const maxElement = Math.max.apply(null, numbers);
console.log('Maximum Element:', maxElement);
Output
Minimum Element: 1 Maximum Element: 8
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