สมมติว่าเราต้องเขียนฟังก์ชันที่รับอาร์เรย์ของสตริง/ตัวเลข และคืนค่าดัชนีของไอเท็มที่ปรากฏบ่อยที่สุด เราจะวนลูปผ่านอาร์เรย์และสร้าง frequencyMap จากนั้นคืนค่าดัชนีที่มีความถี่สูงสุด
โค้ดสำหรับทำเช่นนี้คือ
ตัวอย่าง
const arr1 = [12, 5, 6, 76, 23, 12, 34, 5, 23, 34, 65, 34, 22, 67, 34]; const arr2 = [12, 5, 6, 76, 23, 12, 34, 5, 23, 34]; const mostAppearances = (arr) => { const frequencyMap = {}; arr.forEach(el => { if(frequencyMap[el]){ frequencyMap[el]++; }else{ frequencyMap[el] = 1; }; }); let highest, frequency = 0; Object.keys(frequencyMap).forEach(key => { if(frequencyMap[key] > frequency){ highest = parseInt(key, 10); frequency = frequencyMap[key]; }; }); return arr.indexOf(highest); }; console.log(mostAppearances(arr1)); console.log(mostAppearances(arr2));ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็นดังนี้
6 1