Counting adjacent pairs of words in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a string str that represents a sentence as the only argument.

Our function should count and return the adjacent pair of identical words present in the string str. Our function should check the words ignoring their case, which means ‘it’ and ‘It’ should be counted as identical.

For example, if the input to the function is −

Input

const str = 'This this is a a sample string';

Output

const output = 2;

Output Explanation

Because the repeating words are ‘this’ and ‘a’.

Example

Following is the code −

 Live Demo

const str = 'This this is a a sample string';
const countIdentical = (str = '') => {
   const arr = str.split(' ');
   let count = 0;
   for(let i = 0; i < arr.length - 1; i++){
      const curr = arr[i];
      const next = arr[i + 1];
      if(curr.toLowerCase() === next.toLowerCase()){
         count++;
      };
   };
   return count;
};
console.log(countIdentical(str));

Output

2
raja
Published on 22-Apr-2021 11:29:17
Advertisements