Last active
March 8, 2022 14:02
-
-
Save 0xAliRaza/7bc76db8b68406e3e1a79a41144d4cd6 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* | |
* Date: 08/03/2022 | |
* Task-06: Get second largest number from array | |
* Author: Ali Raza ([email protected]) | |
* | |
*/ | |
/** | |
* | |
* @param {Array} inputArray | |
* @returns {Number} - Second largest number in the given array | |
*/ | |
function secondLargestNumber(inputArray) { | |
// There can't be a second element if array length isn't 2 | |
if (inputArray.length < 2) { | |
return false; | |
} | |
// Check if all the elements are valid numbers | |
if(inputArray.find((el) => !Number.isInteger(el))) return "Please provide a valid numbers array."; | |
// Sort the array in ascending order | |
const sorted = inputArray.sort((a, b) => a - b); | |
// Return the second last element | |
return sorted.at(-2); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment