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 ]