Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Javascript

ค้นหาคำที่พบบ่อยที่สุดในอาร์เรย์โดยใช้ JavaScript


ปัญหา

เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่ใช้อาร์เรย์ arr ของสตริงของตัวอักษรตัวพิมพ์เล็กภาษาอังกฤษเป็นอาร์กิวเมนต์แรก อาร์กิวเมนต์ที่สองของฟังก์ชันของเราคือตัวเลข num (num

ฟังก์ชันของเราควรจะคืนค่าจำนวนองค์ประกอบที่บ่อยที่สุดในอาร์เรย์ arr

คำตอบควรจัดเรียงตามความถี่จากมากไปน้อย หากคำสองคำมีความถี่เท่ากัน คำที่เรียงตามตัวอักษรต่ำกว่าจะมาก่อน

ตัวอย่างเช่น หากอินพุตของฟังก์ชันคือ

ป้อนข้อมูล

const arr = ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"];
const num = 4;

ผลผลิต

const output = ["the", "is", "sunny", "day"];

คำอธิบายผลลัพธ์

"the", "is", "sunny" และ "day" เป็นคำสี่คำที่ใช้บ่อยที่สุด

โดยมีจำนวนครั้งเป็น 4, 3, 2 และ 1 ตามลำดับ

ตัวอย่าง

ต่อไปนี้เป็นรหัส -

const arr = ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"];
const num = 4;
const mostFrequent = (arr = [], num = 1) => {
   const map = {};
   let keys = [];
   for (let i = 0; i < arr.length; i++) {
      if (map[arr[i]]) {
         map[arr[i]]++;
      } else {
         map[arr[i]] = 1;
      }
   }
   for (let i in map) {
      keys.push(i);
   }
   keys = keys.sort((a, b) => {

      if (map[a] === map[b]) {

         if (a > b) {
            return 1;
         } else {
            return -1;
         }
      }
      else {
         return map[b] - map[a];
      }
   })
   .slice(0, num);
   return keys;
};
console.log(mostFrequent(arr, num));

ผลลัพธ์

[ 'the', 'is', 'sunny', 'day' ]