简体   繁体   中英

How to find the second largest element in a user-input Javascript array

I'm working with arrays and I have made the code so that it prompts the user to enter an array of their choice of size. It lets them input each number one by one. I would like so that once this is done the program will then find and print the second largest number in the array but I'm not sure how to go about it.

I would highly like to avoid using infinity or splices just wanted to do something that a newbie like me can understand.

CODE:

 <html> <head> <script type="text/javascript"> //<.-- function show_prompt() { var n = document.frm.text1;value; if (n == "") { alert("Please enter the array size"); } else { var a = new Array(); var temp; for (i = 0; i < n, i++) { var num = prompt("Please enter a number"; " "). document.frm.arrayTxt.value = document.frm.arrayTxt;value + num + "\n"; a[i] = parseInt(num). } document.frm.text1;value = "". document.frm.arrayTxt;value = "": } } //--> </script> </head> <body> <form name="frm"> <center> <hr color="red"> Enter the array size : <input type="text" name="text1"><br><br> <input type="button" onclick="show_prompt()" value="Submit"> <br><br> <textarea name="arrayTxt" rows="10" cols="4"></textarea><br> </center> </form> </body> </html>

You can use a simple for loop, storing the largest and second largest elements, in O(n) time. There is no need to sort the array, which is very inefficient for larger arrays.

let largest = Number.MIN_SAFE_INTEGER, largest2 = largest;
for(const num of a){
    if(num > largest){
       largest2 = largest;
       largest = num;
    } else if(num > largest2){
       largest2 = num;
    }
}
console.log(largest2);

If you need the strictly second largest element, you can remove the duplicates from the array using Set .

a = [...new Set(a)];//add this before the loop

The easiest option is probably to simply sort the array and select the second element. JavaScript Arrays nowadays actually support sorting an array by passing a comparison function .

[2, 5, 3, 1, 4].sort((a, b) => b - a); // [5, 4, 3, 2, 1]

Simply speaking, if the function returns a value < 0 , a is inserted before b, if it returns a value > 0 it a is insterted behind b. If it returns 0 nothing is changed. b - a means "if a > b , move it to the front", resulting in an array sorted highest to lowest. Annoyingly, if you don't pass in a comparison function, the elements are converted to strings and then sorted low to high ( [1, 5, 10, 20] would be sorted [1, 10, 20, 5] ).

To select the second hightest element you would simply select the second index:

a.sort((a, b) => b - a)[1];

Keep in mind, that after calling sort() , the original array will be changed as well.

A different approach would be more hands on, similar to finding the max value.

let max = 0, secondMax = 0;
for (let i = 0; i < a.length; i++) {
    if (a[i] >= max) {
        secondMax = max;
        max = a[i];
    } else if (a[i] > secondMax) {
        secondMax = a[i];
    }
}

This can be slightly more efficient when dealing with large arrays. But since you fill your array with user input, I would choose the first version. It is much shorter and more readable.


NOTE:

The so called "arrow notation" (a, b) => b - a is simply a shorthand for function (a, b) { return b - a; } function (a, b) { return b - a; } . There is more to it, namely arrow functions inheriting this from the creation context, but this has no impact in this specific example.

You could try this:

var numArray = [21, 81, 3847, 218];
numArray.sort((a, b) => b - a); // [3847, 218, 81, 21]
numArray = [...new Set(numArray)]; // Removes duplicates
console.log(numArray[1]); // Returns 218

This basically sorts the array in descending order, and selects the second number via index.

You could just sort the array and return the second number. This should work fine:


var a = [5,3,1,6,8,3,9];
var sorted = a.sort((a, b) => b - a);
alert(a[1])

This is mine:

var first = 0;
var second = 0;
array.forEach(number => {
    if (number > first) {
        second = first;
        first = number;
    }
    else if (number > second) second = number;
});

I believe this is more efficient than a sort but I'm not sure. It might be a more readable solution but it's definitely more over-engineered.

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