เราต้องเขียนฟังก์ชันที่รับอาร์เรย์และคืนสมาชิกที่มีความถี่เป็นอันดับสองมากที่สุด
ตัวอย่าง: [2, 5, 4, 3, 2, 6, 5, 5, 7, 2, 5] → 5 ปรากฏ 4 ครั้ง, 2 ปรากฏ 3 ครั้ง → ผลลัพธ์คือ 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