두 개의 문자열 배열이 있다고 가정합니다. 하나는 일부 단어를 나타내고 다른 하나는 다음과 같은 문장을 나타냅니다. -
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 }