Skip to content

Instantly share code, notes, and snippets.

@quangnd
Last active April 29, 2019 12:04
Show Gist options
  • Save quangnd/e9a98f3103a5f0eb740ac44a6f2d8292 to your computer and use it in GitHub Desktop.
Save quangnd/e9a98f3103a5f0eb740ac44a6f2d8292 to your computer and use it in GitHub Desktop.
Find the second largest number in array
Write a function named getSecondLargest. This function has one parameter: an array of numbers. The function must find and return the second largest number in.
Sample input
`
nums = [2,3,6,6,5]
getSecondLargest(nums)
`
Sample output
`5`
/**
* Return the second largest number in the array.
* @param {Number[]} nums - An array of numbers.
* @return {Number} The second largest number in the array.
**/
// In 34 years old man's mind
function getSecondLargest(nums) {
let largestNum = findLargestNum(nums);
let filteredArr = nums.filter(num => num !== largestNum);
return findLargestNum(filteredArr);
}
function findLargestNum(nums) {
let largestNum = nums[0];
for (let i = 0; i < nums.length; i++) {
if (largestNum < nums[i + 1]) {
largestNum = nums[i + 1];
}
}
return largestNum;
}
// Using Math.max built-in function
function getSecondLargest(nums) {
const max = Math.max(...nums)
return Math.max(...nums.filter(x => x !== max))
}
// Using only one for loop
function getSecondLargest(nums) {
let first = nums[0];
let second = -1;
for (let i = 0; i < nums.length; i++) {
if (nums[i] > first) {
second = first;
first = nums[i];
}
if (nums[i] > second && nums[i] < first) {
second = nums[i];
}
}
return second;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment