DEV Community

[Comment from a deleted post]
Collapse
 
sqnkov profile image
Atanas Georgiev Sqnkov • Edited

Well, how about if we simply filter out the largest num from the original array, and serve an array wihtout it.

function getSecondLargest(nums) {
    let largestNum = Math.max(...nums);
    let filteredNums = [];
    let secondLargest;

    for(let i = 0; i < nums.length; i++) {
        if (nums[i] !== largestNum) {
            filteredNums.push(nums[i]);
        }
    }

    return Math.max(...filteredNums);
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
wahidibrahimy profile image
Wahid Ibrahimy

function getSecondLargest(nums) {
const max=Math.max(...nums);
return Math.max(...nums.filter(x=>x!==max))
}