Jonathan Mporampora
Jonathan Mporampora

Reputation: 31

Switch the vowels in the same word

How can i switch the vowels in a string to where the first vowel is switch with the last vowel and the second vowel is switched with the second to last vowel and so on and so forth? I've tried to split the input string and attempt an embedded for loop, but I can't seem to figure out where to go from there.

function reverseVowels(input) {
  let vowels = ['a','e','i','o','u']
  let newArr = input.split('')
  let result = [];
  for (i = 0; i < newArr.length; i++){
    for (j = 0; j < newArr.length; j++)
      if (newArr[i] === vowels[i] && newArr[j] === vowels[i]) {
        newArr[i] = newArr[j]
      }
  }
  return result;
}

Thank you in advance

Upvotes: 0

Views: 166

Answers (3)

phi-rakib
phi-rakib

Reputation: 3302

Get all the vowels of the input and then reverse it. At last, replace the original arrays vowel with the filtered one.

function reverseVowels(input) {
  const vowels = ['a', 'e', 'i', 'o', 'u'];
  const a = input
    .split('')
    .filter((x) => vowels.includes(x))
    .reverse();
  let count = 0;
  return [...input].map((x) => (vowels.includes(x) ? a[count++] : x)).join('');
}

console.log(reverseVowels('ahije'));
console.log(reverseVowels('axeyuzi'));

Upvotes: 1

Cory Harper
Cory Harper

Reputation: 1055

The most simple solution I can think of is to do a sort of in place reversal where you skip any characters that are not vowels:

function reverseVowels(input) {
  const vowels = new Set(['a','e','i','o','u']);
  const result = input.split('')
  const vowelIndeces = result.reduce((acc, char, i) => {
    if (vowels.has(char)) {
      acc.push(i);
    }

    return acc;
  }, []);
  let i = 0;
  let j = vowelIndeces.length - 1;

  while (j > i) {
    const ref = result[vowelIndeces[i]];
    result[vowelIndeces[i]] = result[vowelIndeces[j]];
    result[vowelIndeces[j]] = ref;
    j--;
    i++;
  }

  return result;
}

Upvotes: 1

ginga_ninja217
ginga_ninja217

Reputation: 92

I would have a runner start from each end. So left would start at index 0 and increase until it hit a vowel (or end of the string, but I'll let you handle edge cases). Once that happens, use a runner right to start at the end and decrease until it hits a vowel. Swap them and repeat until the pointers cross.

Upvotes: 0

Related Questions