สมมติว่าเรามีสตริงสองอาร์เรย์ อันหนึ่งแทนคำบางคำและอีกชุดหนึ่งเป็นประโยคแบบนี้ -
const names= ["jhon", "parker"]; const sentences = ["hello jhon", "hello parker and parker", "jhonny jhonny yes parker"];
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์สตริงดังกล่าวสองอาร์เรย์
ฟังก์ชันควรเตรียมและส่งคืนอ็อบเจ็กต์ที่มีสตริงของอาร์เรย์แรก (ชื่อ) ที่แมปกับจำนวนในอาร์เรย์ประโยค
ดังนั้น สำหรับอาร์เรย์เหล่านี้ ผลลัพธ์ควรมีลักษณะดังนี้ −
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 }