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

Counting adjacent pairs of words in JavaScript


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 −

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