I have an integer array like this :
arr[20,120,111,215,54,78];
I need a function taking an array as its argument and returning the second largest element of that array.
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; };
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));
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
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.
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:
The 2nd largest element could be interpreted as:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With