Last active
July 12, 2018 21:15
-
-
Save brianfiszman/01b8fa410d4e41f6c509a31c40595e50 to your computer and use it in GitHub Desktop.
Get second largest number of an array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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