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

การนับจำนวนครั้งที่คำปรากฏในประโยคอย่างแม่นยำใน JavaScript

มีอาร์เรย์คำ (names) และอาร์เรย์ประโยค (sentences) ต้องนับจำนวนครั้งที่แต่ละคำใน names ปรากฏใน sentences (ต้องจับคู่คำเต็ม ไม่รวมคำที่เป็นส่วนหนึ่งของคำอื่น)

ตัวอย่าง: names=['jhon','parker'], sentences=['hello jhon', 'hello parker and parker', 'jhonny jhonny yes parker'] → {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 }