How to use Math.max() Method In Javascript
Here, like in Approach 2, rather than having three variables, we will use the Math.max() function to iterate and find the three largest elements.
Example: This example demonstrated finding the three largest elements in an array by using the ‘Math.max’ function to find the three largest elements in JavaScript.
//Using Math.max() function
function largestThreeElements(arr) {
const firstLargestEle = Math.max(...arr);
arr = arr.filter((num) => num !== firstLargestEle);
const secondLargestEle = Math.max(...arr);
arr = arr.filter((num) => num !== secondLargestEle);
const thirdLargestEle = Math.max(...arr);
return {
"First Largest Element in Array": firstLargestEle,
"Second Largest Element in Array": secondLargestEle,
"Third Largest Element in Array": thirdLargestEle,
};
}
const inputArray = [12, 56, 7, 89, 43, 21];
const outputElements =
largestThreeElements(inputArray);
console.log(outputElements);
Output
{ 'First Largest Element in Array': 89, 'Second Largest Element in Array': 56, 'Third Largest Element in Array': 43 }
JavaScript Program to Find the Largest Three Elements in an Array
In this article, we are given an array of numbers, we need to find the largest three elements in an array in JavaScript. We will explore the easiest and most efficient code of each approach and also go through the output of the code.
Contact Us