Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

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


ปัญหา

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

ฟังก์ชันควรคืนสมาชิก num ตัวที่พบบ่อยที่สุดในอาร์เรย์ arr

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

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

Input

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

Output

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

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

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

จำนวนครั้งคือ 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' ]