Given an array find second largest number
Code
let arr=[12,9,13,34,-45,12,67]
let unique = [...new Set(arr)]
console.log("Unique Array:",unique)
unique.sort((a,b)=>b-a)
console.log("Sorted Array:",unique)
console.log("Second Largest Number:",unique[1])
Output:
[ 12, 9, 13, 34, -45, 67 ]
[ 67, 34, 13, 12, 9, -45 ]
Second Largest Number: 34
In form of function:
function findNthLargest(arr,n){
let unique = [...new Set(arr)]
unique.sort((a,b)=>b-a)
if (unique.length < n){
throw new Error("Array can't have nth largest number")
}else{
return unique[n-1]
}
}
let arr=[12,9,13,34,-45,12,67]
let n=3
console.log(n + "th Largest Number:" + findNthLargest(arr,n))
Output:
3th Largest Number:13
No comments:
Post a Comment