- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Vowel gaps array in JavaScript
We are required to write a JavaScript function that takes in a string with at least one vowel, and for each character in the string we have to map a number in a string representing its nearest distance from a vowel.
For example: If the string is −
const str = 'vatghvf';
Output
Then the output should be −
const output = [1, 0, 1, 2, 3, 4, 5];
Therefore, let’s write the code for this function −
Example
The code for this will be −
const str = 'vatghvf'; const nearest = (arr = [], el) => arr.reduce((acc, val) => Math.min(acc, Math.abs(val - el)), Infinity); const vowelNearestDistance = (str = '') => { const s = str.toLowerCase(); const vowelIndex = []; for(let i = 0; i < s.length; i++){ if(s[i] === 'a' || s[i] === 'e' || s[i] === 'i' || s[i] === 'o' || s[i] === 'u'){ vowelIndex.push(i); }; }; return s.split('').map((el, ind) => nearest(vowelIndex, ind)); }; console.log(vowelNearestDistance(str));
Output
The output in the console will be −
[ 1, 0, 1, 2, 3, 4, 5 ]
- Related Articles
- Removing last vowel - JavaScript
- Counting occurrences of vowel, consonants - JavaScript
- Distance to nearest vowel in a string - JavaScript
- Deleting the last vowel from a string in JavaScript
- Vowel, other characters and consonant difference in a string JavaScript
- CSS Grid Gaps
- Finding the length of longest vowel substring in a string using JavaScript
- Alternate vowel and consonant string in C++
- Alternate vowel and consonant string in C/C++?
- Program to count sorted vowel strings in Python
- How to remove gaps between bars in Matplotlib bar chart?
- Chunking array within array in JavaScript
- Java program to check occurence of each vowel in String
- Java program to check occurrence of each vowel in String
- Reduce array in JavaScript

Advertisements