[SOLVED] javascript function to find the second largest element in an array

Issue

I am completing the hackerrank’s 10 days of javascript challenge. The question:

write a function to take an array as an argument and then return the second largest element in the array.

I have written the code but my code is returning the largest element and not the second largest as asked.

function getSecondLargest(nums) {
    // Complete the function
    var largest=nums[0];
    for(let i=1;i<nums.length;++i)
    {
        if(nums[i]>largest)
        largest=nums[i];
    }
    var large=nums[0];
    for(let j=1;j<nums.length;++j)
    {
        if(large<nums[j]&&large<largest)
        large=nums[j];
    }
    return large;
}

When input array nums={2,3,6,6,5} the result is coming 6 while expected output is 5. Please help and point out the errors in the function code below.

Solution

Just one minor change:

Use nums[j]<largest instead of large<largest in the second for loop

function getSecondLargest(nums) {
    // Complete the function
    var largest=nums[0];
    for(let i=1;i<nums.length;++i)
    {
        if(nums[i]>largest)
        largest=nums[i];
    }
    var large;
    
    //To ensure that the selected number is not the largest
    for(let j=0;j<nums.length;++j)
    {
        if (nums[j] !== largest){
            large = nums[j];
            break;
        }
    }
    for(let j=1;j<nums.length;++j)
    {
        if(large<nums[j]&&nums[j]!=largest)
            large=nums[j];
        else
            
        console.log(large)
    }
    return large;
}

var secondLargest = getSecondLargest([6,3,6,6,5]);
console.log("Second largest number", secondLargest);

Answered By – Deepak Terse

Answer Checked By – Cary Denson (BugsFixing Admin)

Leave a Reply

Your email address will not be published.