An Interest In:
Web News this Week
- April 26, 2024
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
Some of Our Sources
View All Sources
April 16, 2022 06:51 pm GMT
Original Link: https://dev.to/ganeshshetty195/find-the-second-largest-number-in-an-unsorted-array-without-any-built-in-method-in-javascript-2lo2
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:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To