Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 16, 2022 06:51 pm GMT

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>

Original Link: https://dev.to/ganeshshetty195/find-the-second-largest-number-in-an-unsorted-array-without-any-built-in-method-in-javascript-2lo2

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To