Skip to content

Instantly share code, notes, and snippets.

@brianfiszman
Last active July 12, 2018 21:15
Show Gist options
  • Save brianfiszman/01b8fa410d4e41f6c509a31c40595e50 to your computer and use it in GitHub Desktop.
Save brianfiszman/01b8fa410d4e41f6c509a31c40595e50 to your computer and use it in GitHub Desktop.
Get second largest number of an array
/**
* Return the second largest number in the array.
* @param {Number[]} nums - An array of numbers.
* @return {Number} The second largest number in the array.
**/
const getSecondLargest = nums =>
nums.length > 1
? (function secondLargest(sortedNums, n) {
return sortedNums[n] !== sortedNums[n - 1] || n === 1
? sortedNums[n - 1]
: secondLargest(sortedNums, --n);
})(nums.map(Number).sort((a, b) => a - b), nums.length - 1)
: nums[0];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment