สมมติว่าเรามีสตริงที่มีตัวอักษรบางตัวคั่นด้วยช่องว่างเช่นนี้ -
const str = 'a b c d a v d e f g q';
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงดังกล่าว ฟังก์ชันควรเตรียมอาร์เรย์ความถี่ของออบเจ็กต์ที่มีตัวอักษรและการนับ
ตัวอย่าง
รหัสสำหรับสิ่งนี้จะเป็น −
const str = 'a b c d a v d e f g q';
const countFrequency = (str = '') => {
const result = [];
const hash = {};
const words = str.split(" ");
words.forEach(function (word) {
word = word.toLowerCase();
if (word !== "") {
if (!hash[word]) {
hash[word] = { name: word, count: 0 };
result.push(hash[word]);
};
hash[word].count++;
};
});
return result.sort((a, b) => b.count − a.count)
}
console.log(countFrequency(str)); ผลลัพธ์
และผลลัพธ์ในคอนโซลจะเป็น −
[
{ name: 'a', count: 2 },
{ name: 'd', count: 2 },
{ name: 'b', count: 1 },
{ name: 'c', count: 1 },
{ name: 'v', count: 1 },
{ name: 'e', count: 1 },
{ name: 'f', count: 1 },
{ name: 'g', count: 1 },
{ name: 'q', count: 1 }
]