- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 }
- Related Articles
- Count the number of data types in an array - JavaScript
- Count of number of given string in 2D character array in C++
- How can I split an array of Numbers to individual digits in JavaScript?
- Search from an array of objects via array of string to get array of objects in JavaScript
- Removing comments from array of string in JavaScript
- Find the shortest string in an array - JavaScript
- Deep count of elements of an array using JavaScript
- Find average of each array within an array in JavaScript
- Convert array of object to array of array in JavaScript
- Find Surpasser Count of each element in array in C++
- Find closest index of array in JavaScript
- Returning the value of (count of positive / sum of negatives) for an array in JavaScript
- Find the closest value of an array in JavaScript
- How to join JavaScript array of string
- Summing array of string numbers using JavaScript

Advertisements