मान लीजिए हमारे पास एक स्ट्रिंग है जिसमें कुछ अक्षर व्हाइटस्पेस से अलग हैं जैसे -
const str = 'a b c d a v d e f g q';
हमें एक जावास्क्रिप्ट फ़ंक्शन लिखना है जो ऐसी एक स्ट्रिंग लेता है। फ़ंक्शन को अक्षरों और उनकी गिनती वाले ऑब्जेक्ट्स की एक आवृत्ति सरणी तैयार करनी चाहिए।
उदाहरण
इसके लिए कोड होगा -
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 }
]