If Array is sorted then simple get second last element “arr[arr.length – 2]”. And if Array is not sorted then sort it and do get the second last element of Array.
Find the second largest number in array JavaScript Example
HTML example code:
Using sort method
The simplest way to sort an Array is in JavaScript.
<!DOCTYPE html>
<html>
<body>
<script>
function sLargest(arr) {
const arrSort = arr.sort((a, b) => a - b);
return arrSort[arr.length - 2];
}
var arr = [1, 5, 4, 9, 8];
console.log(sLargest(arr));
</script>
</body>
</html>
Using Math max and other methods without sorting
Frist get the max of the array, then replace max in the array with -infinity and last get the new max.
The performance could be enhanced by not doing a splice but temporarily replacing the max value with -Infinity:
<!DOCTYPE html>
<html>
<body>
<script>
function sLargest(arr) {
var max = Math.max.apply(null, arr),
maxi = arr.indexOf(max);
arr[maxi] = -Infinity;
var secondMax = Math.max.apply(null, arr);
arr[maxi] = max;
return secondMax;
}
var arr = [1, 5, 4, 9, 8];
console.log(sLargest(arr));
</script>
</body>
</html>
Source: https://stackoverflow.com/
Output: It will be the same because using the same Array.
Do comment if you have any doubts and suggestions on this JS Array topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version