Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 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];
The logic is: 'v' is 1 position away from vowel 'a', 'a' is 0 (it's a vowel), 't' is 1 away from 'a', 'g' is 2 away from 'a', and so on.
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 nearest(vowelIndex, ind));
};
console.log(vowelNearestDistance(str));
Output
The output in the console will be ?
[
1, 0, 1, 2,
3, 4, 5
]
How It Works
The solution works in three steps:
- Find vowel positions: Loop through the string and store indices of all vowels in an array
-
Calculate distances: For each character position, find the minimum distance to any vowel position using
Math.abs() -
Map results: Use
map()to transform each character into its nearest vowel distance
Alternative Approach
Here's a more concise version using modern JavaScript features:
const vowelNearestDistanceModern = (str = '') => {
const vowels = 'aeiou';
const s = str.toLowerCase();
// Find all vowel indices
const vowelIndices = [...s].map((char, i) => vowels.includes(char) ? i : null)
.filter(i => i !== null);
// Calculate nearest distance for each position
return [...s].map((_, i) =>
Math.min(...vowelIndices.map(vi => Math.abs(vi - i)))
);
};
const testStr = 'hello';
console.log(vowelNearestDistanceModern(testStr));
[ 1, 0, 2, 2, 0 ]
Conclusion
This algorithm efficiently finds the nearest vowel distance for each character by first collecting vowel positions, then calculating minimum distances. The time complexity is O(n²) where n is the string length.
