Find the second largest number in array JavaScript | Example code

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 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 in JavaScript.

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 -Infininty:

Source: https://stackoverflow.com/

Output: It will be same because using a same Array.

Find the second largest number in array JavaScript

Do comment if you have any doubts and suggestions on this JS Array topic.

Note: All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.