
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Questions & Answers
- Swapping adjacent words of a String in JavaScript
- Counting number of words in a sentence in JavaScript
- Removing letters to make adjacent pairs different using JavaScript
- Counting pairs with range sum in a limit in JavaScript
- Counting number of words in text file using java
- Python - Joining only adjacent words in list
- Unique pairs in array that forms palindrome words in JavaScript
- Program to restore the array from adjacent pairs in Python
- Counting number of 9s encountered while counting up to n in JavaScript
- Counting occurrences of vowel, consonants - JavaScript
- Number of letters in the counting JavaScript
- Count all pairs of adjacent nodes whose XOR is an odd number in C++
- Implementing counting sort in JavaScript
- Counting matching substrings in JavaScript
- Counting divisors of a number using JavaScript
Advertisements