Twice repetitive word count in a string - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a string that contains some words that are repeated twice, we need to count such words.

For example −

If the input string is −

const str = "car bus jeep car jeep bus motorbike truck";

Then the output should be −

3

Example

Following is the code −

const str = "car bus jeep car jeep bus motorbike truck";
const countRepetitive = str => {
   const strArr = str.split(" ");
   let count = 0;
   for(let i = 0; i < strArr.length; i++){
      if(i === strArr.lastIndexOf(strArr[i])){
         continue;
      };
      count++;
   };
   return count;
};
console.log(countRepetitive(str));

Output

Following is the output in the console −

3
raja
Published on 15-Sep-2020 15:20:23
Advertisements