Find the second largest element from array in javascript (Hackerrank problem)

Function Description

Complete the getSecondLargest function in the editor below.

getSecondLargest has the following parameters:

  • int nums[n]: An array of integers number. (The largest number may be dublicate)


  • The second largest number

function getSecondLargest(nums) {
    // Complete the function
    let sLargest=-1;
    let fLargest = 0;  
    for(let i=0; i<nums.length; i++) {
        if(nums[i]> fLargest) {
            sLargest= fLargest;
            fLargest = nums[i];
         if(nums[i]> sLargest && nums[1] < fLargest) {

    return sLargest;

const secondLargestElement = getSecondLargest([2,6,3,90,3,2,67,78])

You May Also Like

About the Author: Sunil Yadav

Hi, This is Sunil Yadav, I am full stack dev. I have a passion for learning and sharing my knowledge with others as publicly as possible.

Leave a Reply

Your email address will not be published.