Click Here ЁЯСЙЁЯП╗ * Check Corona Virus ЁЯжа Cases in Your Country   * India Coronavirus Stats ЁЯжа and Updates cases in State   * рднрд╛рд░рдд рдХреЛрд░реЛрдирд╛рд╡рд╛рдпрд░рд╕ ЁЯжа рдЖрдБрдХрдбрд╝реЗ рдФрд░ рд░рд╛рдЬреНрдп рдореЗрдВ рдорд╛рдорд▓реЗ рдХреА рдЬрд╛рдБрдЪ рдХрд░реЗрдВред   * рдЕрдкрдиреЗ рджреЗрд╢ рдХрд╛ рдХреЛрд░реЛрдирд╛ рд╡рд╛рдпрд░рд╕ ЁЯжа рдЕрдкрдбреЗрдЯ рджреЗрдЦреЗрдВ   * QR Code generator by name or link   * рдЕрдкрдиреЗ рдирд╛рдо рдХрд╛ QR Code рдмрдирд╛рдпреЗ    * рдЕрдкрдиреЗ рдкрд╛рд╕рд╡рд░реНрдб рдХреЛ рдЧреВрдЧрд▓ рдХреА рддрд░рд╣ Secure рдмрдирд╛рдпреЗ    * Generate Google Secure Strong Password

How to get second largest element of array  in JavaScript Hacker Rank Question

 

How to get the second largest element of an array  in JavaScript Hacker Rank Question



Hy Friends, Today we will learn How to get a second largest element of array in JavaScript.

This question asked mostly in Interviews.

We can do resolve this in different ways. So lets' Start.

Let's Assume we have Array 


let arr = [ 100, 23 , 45, 145, 44, 22, 5, 6, 33, 55]



First Way -  First we will sort an array in descending order using the javascript sort function and then get the second index. this will be our second largest element of an array. 


arr.sort( (a,b) => b - a)[1] // output 100


Here I have used the arrow function.


Second Way -  
 Step 1- Second way we will get the max number of the array element and store in a variable.
var highest = Math.max.apply('',arr);


Step 2 -  Get the index of the largest number.

var highestIndex = arr.indexOf(highest);


Step 3 -  Assign zero or negative value to the array (arr) 


arr[highestIndex] = 0 ; // - Infinity , -1


Step 4 -   Now again get max number using Math.max.apply function 



var secondHighest = Math.max.apply('',arr);
// output -> 100


Yeah! You have learned ЁЯШК

I hope you understood and like this article. if you like it so, please give feedback in the comment section.

Post a Comment

Please do not enter any spam link in the comment section.

Previous Post Next Post