เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่ใช้อาร์เรย์ของตัวอักษร ฟังก์ชันควรส่งคืนองค์ประกอบที่ปรากฏเป็นจำนวนครั้งที่ 2 ในอาร์เรย์มากที่สุด
ตัวอย่างเช่น −
หากอาร์เรย์อินพุตเป็น −
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