The most straightforward implementation, without modifying the original array, is to iterate and track the biggest and next biggest:

function nextBiggest(arr) {
  let max = -Infinity, result = -Infinity;

  for (const value of arr) {
    const nr = Number(value)

    if (nr > max) {
      [result, max] = [max, nr] // save previous max
    } else if (nr < max && nr > result) {
      result = nr; // new second biggest
    }
  }

  return result;
}

const arr = ['20','120','111','215','54','78'];
console.log(nextBiggest(arr));
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Variations

The behaviour of returning -Infinity if there's no next maximum value distinct from the maximum value in a non-empty array can be modified at the end of the function, depending on the requirements.

Same as maximum

return result == -Infinity ? max : result;

For an empty array, this will return -Infinity as before, but would otherwise return the same value as the maximum if no next distinct maximum is found.

Return null

return result == -Infinity ? null : result;

Same as above, but the return value of null is more indicative of the nonexistence of a next distinct maximum.

Answer from Ja͢ck on Stack Overflow
🌐
DEV Community
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 - DEV Community
April 19, 2022 - <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> ... #javascript #webdev #css #programming An Overview of Redux and its Middleware for React Applications
Top answer
1 of 10
60

The most straightforward implementation, without modifying the original array, is to iterate and track the biggest and next biggest:

function nextBiggest(arr) {
  let max = -Infinity, result = -Infinity;

  for (const value of arr) {
    const nr = Number(value)

    if (nr > max) {
      [result, max] = [max, nr] // save previous max
    } else if (nr < max && nr > result) {
      result = nr; // new second biggest
    }
  }

  return result;
}

const arr = ['20','120','111','215','54','78'];
console.log(nextBiggest(arr));
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Variations

The behaviour of returning -Infinity if there's no next maximum value distinct from the maximum value in a non-empty array can be modified at the end of the function, depending on the requirements.

Same as maximum

return result == -Infinity ? max : result;

For an empty array, this will return -Infinity as before, but would otherwise return the same value as the maximum if no next distinct maximum is found.

Return null

return result == -Infinity ? null : result;

Same as above, but the return value of null is more indicative of the nonexistence of a next distinct maximum.

2 of 10
50

Original answer

var secondMax = function (){ 
    var arr = [20, 120, 111, 215, 54, 78]; // use int arrays
    var max = Math.max.apply(null, arr); // get the max of the array
    arr.splice(arr.indexOf(max), 1); // remove max from the array
    return Math.max.apply(null, arr); // get the 2nd max
};

demo

Update 1

As pointed out by davin the performance could be enhanced by not doing a splice but temporarily replacing the max value with -Infininty:

var secondMax = function (arr){ 
    var max = Math.max.apply(null, arr), // get the max of the array
        maxi = arr.indexOf(max);
    arr[maxi] = -Infinity; // replace max in the array with -infinity
    var secondMax = Math.max.apply(null, arr); // get the new max 
    arr[maxi] = max;
    return secondMax;
};

Anyway, IMHO the best algorithm is Jack's. 1 pass, with conversion to number. Mine is just short, using builtin methods and only wanted to provide it as an alternative, to show off all the different ways you can achieve the goal.

Update 2

Edge case with multiple values.

As comments pointed it out: this solution "does not work" if we have an array like [3, 3, 5, 5, 5, 4, 4]. On the other hand it would be also a matter of interpretation what we would consider "the 2nd largest element". In the example we have:

  1. 3 elements with the largest value (5) at indices: 2,3,4
  2. 2 elements with the second largest value (4) at indices: 5,6
  3. 2 elements with the second smallest value (3) at indices: 1,2

The 2nd largest element could be interpreted as:

  1. the 2nd (largest element) - 5 at index 3 - assuming that there is an order, and that we aim for a unique value
  2. the (2nd largest) element - 4 at index 5 - assuming that there is an order, and that we aim for a unique value
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › find-second-largest-element-array
Second Largest Element in an Array - GeeksforGeeks
// JavaScript program to find the second largest element in the array // using two traversals function getSecondLargest(arr) { let n = arr.length; let largest = -1, secondLargest = -1; // Finding the largest element for (let i = 0; i < n; i++) { if (arr[i] > largest) largest = arr[i]; } // Finding the second largest element for (let i = 0; i < n; i++) { // Update second largest if the current element is greater // than second largest and not equal to the largest if (arr[i] > secondLargest && arr[i] !== largest) { secondLargest = arr[i]; } } return secondLargest; } let arr = [12, 35, 1, 10, 34, 1]; console.log(getSecondLargest(arr));
Published   February 10, 2025
🌐
Medium
646634.medium.com › pop-quiz-how-do-you-find-the-second-largest-number-in-an-array-in-javascript-b08bb6bb4617
Pop quiz: How do you find the second largest number in an array in JavaScript? | by Saul Feliz | Medium
July 14, 2020 - function findSecondLargest(arr) { const distinct = [...new Set(arr)]; const maxNum = Math.max(...distinct); const filteredMaxOut = distinct.filter((num) => num < maxNum); const secondMax = Math.max(...filteredMaxOut); return secondMax; } Not necessarily better, considering more memory usage and similar time complexity, but it’s good to know a few ways to solve this problem. And remember… · Grit > talent. JavaScript · Duplicate · Arrays ·
🌐
Medium
umarfarooquekhan.medium.com › find-the-second-largest-element-in-an-array-using-a-single-loop-in-javascript-dbeb0c42c58d
Find The Second Largest Element In An Array Using A Single Loop In JavaScript | by Umar Farooque Khan | Medium
December 2, 2023 - To find the second largest element in an array using a single loop in JavaScript, you can iterate over the array and keep track of the largest and second-largest elements as you go.
🌐
OneCompiler
onecompiler.com › javascript › 3xj9yx24j
Second Largest Number - JavaScript - OneCompiler
Below are couple of ways to use arrow function but it can be written in many other ways as well. ... const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] const squaresOfEvenNumbers = numbers .filter((ele) => ele % 2 == 0) .map((ele) => ele ** 2) console.log(squaresOfEvenNumbers) ...
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-program-to-find-second-largest-element-in-an-array
JavaScript - Find Second Largest Element in an Array - GeeksforGeeks
July 23, 2025 - The unique elements are sorted in descending order. The second largest element is at index 1 after sorting. To find the second largest element using iteration, initialize two variables, largest and secondLargest, to -Infinity.
🌐
W3Resource
w3resource.com › javascript-exercises › javascript-function-exercise-11.php
JavaScript function: Find the second lowest and second greatest numbers from an array - w3resource
Write a JavaScript function that takes an array of numbers and finds the second lowest and second greatest numbers, respectively. ... // Define a function named Second_Greatest_Lowest that finds the second smallest and second largest numbers in an array function Second_Greatest_Lowest(arr_num) { // Sort the array in ascending order using a custom comparison function arr_num.sort(function(x, y) { return x - y; }); // Initialize an array uniqa with the first element of the sorted array var uniqa = [arr_num[0]]; // Initialize an array result to store the second smallest and second largest numbers
Find elsewhere
🌐
Quora
quora.com › How-do-we-find-the-second-largest-number-in-an-unsorted-array-using-JavaScript
How do we find the second-largest number in an unsorted array using JavaScript? - Quora
Answer: 1. Initialize two variables first and second to INT_MIN as first = second = INT_MIN 2. Start traversing the array, a) If the current element in array say arr[i] is greater than first.
🌐
Open Tech Guides
opentechguides.com › askotg › question › 32 › javascript-find-second-largest-value-in-an-array
Javascript: find second largest value in an array?
How to find second largest value without sorting the array or latering its contents? javascript array second-largest ... function secondLargest(arr) { var max1st = arr[0]; var max2nd = 0; for(var i=0; i<arr.length; i++) { if(arr[i] > max1st) { max2nd = max1st; max1st = arr[i]; } else if(arr[i] > max2nd && arr[i] != max1st) { max2nd = arr[i]; } } return max2nd; } console.log(secondLargest([100,2,4,54,27,98,99])); console.log(secondLargest([10,22,48,54,27,8])); console.log(secondLargest([2,4,54,27,98,99])); console.log(secondLargest([21,42,87,27,8,99])); console.log(secondLargest([10,10,10,5,6,7,8]));
🌐
GeeksforGeeks
geeksforgeeks.org › javascript-program-to-find-second-largest-element-in-an-array
JavaScript – Find Second Largest Element in an Array | GeeksforGeeks
January 29, 2025 - After the reduction, acc[1] holds the second largest element. ... Given a nested array of numbers, we need to find and return the largest element present in the array. Below are the approaches to detecting the largest element in an array of Numbers (nested) in JavaScript: Table of Content Iterative ApproachRecursive ApproachIterative ApproachUse a nested loop to t
🌐
HackerRank
hackerrank.com › contests › 7days-javascript › challenges › find-second-largest-number-in-an-array
Solve Day 3: Find the Second Largest Number in an Array
Output the 2nd largest number in an array in JavaScript. Solving code challenges on HackerRank is one of the best ways to prepare for programming interviews.
🌐
HackerRank
hackerrank.com › contests › 7days-javascript › challenges › find-second-largest-number-in-an-array › forum
Day 3: Find the Second Largest Number in an Array ...
Join over 28 million developers in solving code challenges on HackerRank, one of the best ways to prepare for programming interviews.
🌐
NamasteDev
namastedev.com › home › core programming languages › c/c++ › find the second largest number in an array
Find the Second Largest Number in an Array - NamasteDev Blogs
May 30, 2025 - After loop, check if secondLargest was updated. If not, return message. Time Complexity: O(n) – Single pass through the array. Space Complexity: O(1) – Constant space used for two variables. ... function secondLargest(arr) { if (arr.length < 2) return "Array should have at least two numbers"; let first = -Infinity, second = -Infinity; for (let i = 0; i < arr.length; i++) { if (arr[i] > first) { second = first; first = arr[i]; } else if (arr[i] > second && arr[i] !== first) { second = arr[i]; } } return second === -Infinity ?
🌐
PrepBytes
prepbytes.com › home › arrays › finding second largest number in array
Finding Second Largest Number in Array
June 8, 2023 - In this approach, we will use two variables to keep track of the largest and second-largest elements so far. Let’s see an algorithm of this approach. ... If the current element in the array say arr[i] is greater than largest.
🌐
Medium
rvindjitta11.medium.com › find-the-second-largest-number-in-an-array-by-javascript-8ccd10162530
Find the Second Largest Number in an Array by JavaScript. | by Rvind Jitta | Medium
May 11, 2021 - Array=[1,2,3,4,5] Array.splice(1,1)//output Array=[1,3,4,5] ... down is the code of main function processData(),go through the comments in the code for detailed understanding · The below source code includes complete code ,which includes function math.max() ,and we called that function in our main function processData
🌐
DEV Community
dev.to › slimpython › 3-ways-to-find-second-largest-number-in-array-javascript-24l9
3 ways to find second largest number in array JavaScript - DEV Community
August 16, 2022 - In this video i have explained 3 ways you can find the second largest number in any array in JavaScript, and also given their time complexity.