I'm trying to find the 2nd largest number in an array, and square this number.
arr = [1,8,6,2,5,4,8,3,7]
should return 49 (7 squared)
arr = [1,1]
should return 1 (1 squared)
I've tried the code below and it works on the first array and return 49, but on the second array with [1,1] it returns NaN.
The problem is with the secondLargest variable--it returns undefined on the console.log. It may be because I'm using set, but I don't understand why it's not just returning 1 instead of undefined.
var maxArea = function(height) {
let secondLargest = Array.from([...new Set(height)]).sort((a,b) => b-a)[1]
console.log(secondLargest);
return Math.pow(secondLargest, 2);
};
Set
eliminates duplicates, so the array [1, 1]
gets turned into [1]
. There is no second element, so you get undefined when trying to access index 1
. Since this is not what you want, sort the array directly without creating a Set
, or take the first element when there is no second element.
function maxArea(height) { const sorted = [...new Set(height)].sort((a,b) => ba); return (sorted[1]?? sorted[0]) ** 2; } console.log(maxArea([1, 1])); console.log(maxArea([1,8,6,2,5,4,8,3,7]));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.