मान लीजिए हमारे पास स्ट्रिंग्स की दो सरणियां हैं, एक कुछ शब्दों का प्रतिनिधित्व करती है और दूसरी कुछ वाक्यों का जैसे -
const names = ["jhon", "parker"]; const sentences = ["hello jhon", "hello parker and parker", "jhonny jhonny yes parker"];
हमें एक जावास्क्रिप्ट फ़ंक्शन लिखना है जो ऐसी दो स्ट्रिंग सरणियां लेता है। फ़ंक्शन को एक ऑब्जेक्ट तैयार करके लौटाना चाहिए जिसमें पहली (नाम) सरणी के स्ट्रिंग्स दूसरी सरणी में उनकी गिनती के साथ मैप हों।
इसलिए, इन सरणियों के लिए, आउटपुट ऐसा दिखना चाहिए -
const output = {
"jhon": 1,
"parker": 3
};उदाहरण
इसके लिए कोड होगा -
const names = ["jhon", "parker"];
const sentences = ["hello jhon", "hello parker and parker", "jhonny jhonny yes parker"];
const countAppearances = (names = [], sentences = []) => {
const pattern = new RegExp(names.map(name => `\\b${name}\\b`).join('|'), 'gi');
const res = {};
for (const sentence of sentences) {
for (const match of (sentence.match(pattern) || [])) {
res[match] = (res[match] || 0) + 1;
}
}
return res;
};
console.log(countAppearances(names, sentences));आउटपुट
कंसोल में आउटपुट होगा -
{ jhon: 1, parker: 3 }