Count and return the number of characters of str1 that makes appearances in str2 using JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in two strings, str1 and str2 as the first and second argument respectively.

Our function should count and return the number of characters of str1 that makes appearances in str2 as well, and if there are repetitive appearances, we have to count them separately.

For example, if the input to the function is

Input

const str1 = 'Kk';
const str2 = 'klKKkKsl';

Output

const output = 5;

Example

Following is the code −

 Live Demo

const str1 = 'Kk';
const str2 = 'klKKkKsl';
var countAppearances = (str1 = '', str2 = '') => {
   const map = {}
   for(let c of str1) {
      map[c] = true
   }
   let count = 0
   for(let c of str2) {
      if(map[c]) {
         count+=1
      }
   }
   return count
};
console.log(countAppearances(str1, str2));

Output

5
raja
Published on 24-Apr-2021 10:01:30
Advertisements