Computer >> Computer tutorials >  >> Programming >> Javascript

Find the exact individual count of array of string in array of sentences in JavaScript


Suppose we have two arrays of strings, one representing some words and the other some sentences like this −

const names= ["jhon", "parker"];
const sentences = ["hello jhon", "hello parker and parker", "jhonny jhonny
yes parker"];

We are required to write a JavaScript function that takes in two such arrays of strings.

The function should prepare and return an object that contains the strings of the first (names) array mapped against their count in the sentences array.

Therefore, for these arrays, the output should look something like this −

const output = {
   "jhon": 1,
   "parker": 3
};

Example

The code for this will be −

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));

Output

And the output in the console will be −

{ jhon: 1, parker: 3 }