Hi! I have a problem. I can’t find the second largest number from an array. This is where I get stack https://codepen.io/raul-rogojan/pen/VwpdpeY?editors=0010 . I know that there is 1 think that I am missing but I don;t know what
@SempervivumJun 07.2021 — #Seems to me that one needs two runs of the loop: First find the largest item and then the second largest: ``<i> </i>var arr = [2000,500,100,2,80,1,50,90,4,50,6,3,30,60,2500,3000,1000,9,40]; var largest = 0; var secondLargest = 0
for(var i = 0; i < arr.length; i++) {
if(largest < arr[i]) { largest = arr[i]; } } for(var i = 0; i < arr.length; i++) {
@NogDogJun 07.2021 — #Maybe just sort it in descending order and then grab the first 2 elements? [code=javascript] arr.sort(function(a, b){return b - a}); console.log('cel mai mare numar este' + arr[0]); console.log('al doilea cel mai mare numar este' + arr[1]); [/code]
@NogDogJun 08.2021 — #> @RaulRogojan#1632677 I was imagining that the arr order need to stay the same
You could then make a copy of the array, and sort the copy. Gets a bit resource intensive for very large arrays, for some undefined value of "very large". 🤷♂️
@codyhillauthorJun 12.2021 — #@NogDog#1632694 Yeah, I did not take that into account, I was trying to give myself a challenge and trying to figure how things work. I noticed that I don't need a second if in the loop and it works like this ``<i> </i>var arr = [2000,500,100,2,80,1,50,90,4,50,6,3,30,60,2500,55,3000,1000,9,40]; var largest = arr[0]; var secondLargest = arr[0];
@NogDogJun 13.2021 — #> @RaulRogojan#1632874 I still do not understand why this works.
When 2000 comes in first, secondLargest will be set to 0 (again), and thenlargest will be set to 2000. Nothing will change until you reach 2500, at which point secondLargest will be updated to 2000 and then 2500 assigned to largest. Then nothing will change until 3000 comes along, so 2500 will be moved to secondLargest and largest set to 3000.
However, one possible problem I see would be if there were another 3000 in the array. Since at that point the if would not fire, since it would not be < the already set 3000, it would be skipped. If the desire in the case of a tie would be that both values should be set to 3000, then I think using <= for the comparison would take care of that.
@tracknutJun 13.2021 — #Depending on how serious this task is, you might also confirm expected and working solutions when the array looks like: var arr = [2000,2000,40];