简体   繁体   中英

Finding the next largest number in an array using JavaScript If…Else Statements

Would you be so kind and explain how "else if" statement in the below piece of code returns the second largest number from an array?

Especially that there is no AND operator (&&) within "else if statement". I mean for ex.:

else if (max2 < array[i] && max1 > array[i])

I found people using this kind of approach on stackOverflow but they did not give any detailed explanations ("why it works"):

 var arr1 = [2, 3, 1, 6, 100, 49, 5, 7, 8, 9]; function getSecondMaxNumber(array) { var max1 = 0; var max2 = 0; for (var i = 0; i <= array.length; i++) { if (max1 < array[i]) { max1 = array[i]; } else if (max2 < array[i]) { max2 = array[i]; } } return max2; } console.log(getSecondMaxNumber(arr1)); 

UPDATE

The above method is wrong as Hassan commented below.

I decided to use:

var arr1 = [2, 3, 1, 6, 100, 49, 5, 7, 8, 9];


function getSecondMaxNumber(array) {
    function sortNumbers(a, b) { //Compare numbers.
        return a - b;
    }
    var arrSorted = array.sort(sortNumbers); //Set up sorting.
    return arrSorted[arrSorted.length - 2]; //Choose the second largest number in an array.
}
console.log(getSecondMaxNumber(arr1)); //Show me that number.

You don't need the && because the if condition has already eliminated the possibility of max1 being less than array[i] . You can't get to the else if condition without the if first failing.

And side note, the loop condition should be < instead of <= .

if (max1 < array[i]) {

If the current number is bigger then the current biggest number, set that number to the biggest number.

} else if (max2 < array[i]) {

If its not the biggest number it may be the second biggest.

Maybe shorter:

 const result = array.reduce(([max, max2], el) => el > max ? [el, max] : el > max2 ? [max, el] : [max, max2], [0,0])[1];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM