How to use loops In Javascript
Here, we will use the JavaScript loop to iterate through the array of elements once. We will keep three variables as (‘firstLargestEle’, ‘secondLargestEle’, and ‘thirdLargestEle’. Firstly, we will initialize the ‘firstLargestEle‘ to the first element of the input array and ‘secondLargestEle‘, and ‘thirdLargestEle‘ to the negative infinity which is used to handle the negative numbers. Later, we will apply the comparision logic in the loop and return the three largest elements from the array.
Example: This example demonstrated finding the largest three elements in an array by using loops to find the three largest elements in JavaScript.
//Using Loops
function largestThreeElements(arr) {
let firstLargestEle = arr[0];
let secondLargestEle = -Infinity;
let thirdLargestEle = -Infinity;
for (const num of arr) {
if (num > firstLargestEle) {
thirdLargestEle = secondLargestEle;
secondLargestEle = firstLargestEle;
firstLargestEle = num;
} else if (num > secondLargestEle) {
thirdLargestEle = secondLargestEle;
secondLargestEle = num;
} else if (num > thirdLargestEle) {
thirdLargestEle = num;
}
}
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.