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
]

Updated on: 17-Oct-2020

64 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements