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

หาคำที่พบบ่อยที่สุด n อันดับแรกจากประโยคใน JavaScript

ปัญหา

รับประโยค str และตัวเลข num นับความถี่แต่ละคำ คืนอาร์เรย์ num คำที่พบบ่อยสุดเรียงจากมากไปน้อย

ตัวอย่าง

const str = 'i am a good coder and i know that i can solve a problem'; 
const num = 2;

คำที่พบบ่อยสุด: 'i' (3 ครั้ง), 'a' (2 ครั้ง) → ผลลัพธ์ ['i', 'a']

โค้ดตัวอย่าง

const str = 'i am a good coder and i know that i can solve a problem'; 
const num = 2; 
const findMostFrequent = (str = '', num = 1) => { 
  const strArr = str.split(' '); 
  const map = {}; 
  strArr.forEach(word => { map[word] = (map[word] || 0) + 1; }); 
  const frequencyArr = Object.keys(map).map(key => [key, map[key]]); 
  frequencyArr.sort((a, b) => b[1] - a[1]); 
  return frequencyArr.slice(0, num).map(el => el[0]); 
}; 
console.log(findMostFrequent(str, num));

ผลลัพธ์

[ 'i', 'a' ]