Znajdź drugą co do wielkości liczbę w tablicy JavaScript za pomocą pętli
const array = [32, 523, 5632, 920, 6000];
let largestNum = array[0];
let secondLargestNum = 0;
for(let i = 1; i < array.length; i++) {
if(array[i] > largestNum) {
secondLargestNum = largestNum;
largestNum = array[i];
}
if else (array[i] !== largestNum && array[i] > secondLargestNum) {
secondLargestNum = array[i];
}
};
console.log("Largest Number in the array is " + largestNum);
console.log("Second Largest Number in the array is " + secondLargestNum);
/* Explanation:
1) Initialize the largestNum as index of arr[0] element
2) Start traversing the array from array[1],
a) If the current element in array say arr[i] is greater
than largestNum. Then update largestNum and secondLargestNum as,
secondLargestNum = largestNum
largestNum = arr[i]
b) If the current element is in between largestNum and secondLargestNum,
then update secondLargestNum to store the value of current variable as
secondLargestNum = arr[i]
3) Return the value stored in secondLargestNum.
*/
Md. Ashikur Rahman