Find the second-highest number in a JavaScript array:
✅ Approach 1: Using Sorting (Simple & Easy)
const arr = [10, 5, 8, 12, 7, 12];
const uniqueSorted = [...new Set(arr)].sort((a, b) => b - a);
const secondHighest = uniqueSorted[1];
console.log("Second highest:", secondHighest);
🟢 Output:
Second highest: 10
✅ Approach 2: Without Sorting (Efficient for Large Arrays)
function findSecondHighest(arr) {
let max = -Infinity;
let secondMax = -Infinity;
for (let num of arr) {
if (num > max) {
secondMax = max;
max = num;
} else if (num > secondMax && num < max) {
secondMax = num;
}
}
return secondMax === -Infinity ? null : secondMax;
}
const arr = [3, 9, 1, 9, 4, 7];
console.log("Second highest:", findSecondHighest(arr));
🟢 Output:
Second highest: 7