假设我们有两个字符串数组,一个数组代表某些单词,另一种则代表这样的句子-
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 }