हमें एक जावास्क्रिप्ट फ़ंक्शन लिखना है जो शाब्दिक मानों की एक सरणी लेता है। फ़ंक्शन को वह तत्व लौटाना चाहिए जो सरणी में दूसरी सबसे अधिक बार आता है।
उदाहरण के लिए -
यदि इनपुट सरणी है -
const arr = [2, 5, 4, 3, 2, 6, 5, 5, 7, 2, 5];
तो आउटपुट होना चाहिए -
const output = 2;
उदाहरण
const arr = [2, 5, 4, 3, 2, 6, 5, 5, 7, 2, 5];
const findSecondMost = (arr = []) => {
const map = {};
arr.forEach(el => {
if (map.hasOwnProperty(el)) {
map[el]++;
} else {
map[el] = 1;
}
});
const sorted = Object.keys(map).sort((a, b) => map[b] - map[a]);
return sorted[1];
};
console.log(findSecondMost(arr));आउटपुट
कंसोल में आउटपुट होगा -
2