DEV Community

Ganesh Shetty
Ganesh Shetty

Posted on • Edited on

Find the second largest number in an unsorted array without any built-in method in JavaScript

I am sure some of you have faced this question in an interview,When asked the same question in a sorted array or if we can use built-in method, this is definitely an easy question to crack, But this is little tricky without these.

But solution is very simple, first finding maximum number then to find second maximum when the array element is maximum we will just skip that element,

<script>
    let array = [10, 30, 35, 20, 30, 25, 90, 89];

    function secondLargestNumber(array) {
        let max = 0;
        let secondMax = 0;

        for (let i = 0; i < array.length; i++) {
            if (array[i] > max) {
                max = array[i];
            }
        }

        for (let i = 0; i < array.length; i++) {
            if (array[i] > secondMax && array[i] !== max) {
                secondMax = array[i];
            }
        }
        return secondMax;
    }
    console.log(secondLargestNumber(array));
</script>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)