
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Distance to nearest vowel in a string - JavaScript
We are required to write a JavaScript function that takes in a string with atleast 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';
Then the output should be −
const output = [1, 0, 1, 2, 3, 4, 5];
Example
Following is the code −
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
Following is the output in the console −
[ 1, 0, 1, 2, 3, 4, 5 ]
- Related Articles
- Deleting the last vowel from a string in JavaScript
- Vowel, other characters and consonant difference in a string JavaScript
- Distance of nearest 0 in binary matrix in JavaScript
- Finding the length of longest vowel substring in a string using JavaScript
- Finding hamming distance in a string in JavaScript
- Vowel gaps array in JavaScript
- Removing last vowel - JavaScript
- Nearest Prime to a number - JavaScript
- Alternate vowel and consonant string in C++
- Python Program to accept string starting with vowel
- Corresponding shortest distance in string in JavaScript
- Java program to check occurence of each vowel in String
- Java program to check occurrence of each vowel in String
- Alternate vowel and consonant string in C/C++?
- Nearest palindrome in JavaScript

Advertisements