with input ‘hello’, output should be ‘holle’
heres my code,
var reverseVowels = function (s) {
// change s into array
// if a, i, u, e, o
// change that item to 'marked'
// also put the index of that marked items into another array
// put the marked items to another array
// sort that marked items array, then reverse it
// // im at here right now
// then put that array inside its original place
let newString = s.split('');
let markedItems = [];
let markedItemsIndex = [];
let count = 0;
for (let i = 0; i < newString.length; i++) {
if (
newString[i] === 'a' ||
newString[i] === 'i' ||
newString[i] === 'u' ||
newString[i] === 'e' ||
newString[i] === 'o'
) {
markedItemsIndex.push(i);
markedItems.push(newString[i]);
newString[i] = 'marked';
}
}
let reversedMarkedItems = markedItems.reverse();
for (let i = 0; i < newString.length; i++) {
if (i === markedItemsIndex[count]) {
console.log('here');
newString[i] = reversedMarkedItems[count];
}
count++;
}
// return [newString, markedItems.reverse(), markedItemsIndex];
return newString;
};
look at the second loop, im checking if the i === markedItemsIndex but my code never goes there, because of that, the ‘here’ never returns.
i’ve checked the type of i and type of markedItemsIndex, they’re both a number. how can i fix this
3
Answers
You should only increment the
count
once the vowel at that index has been handled, i.e inside the if statement (not on every iteration, which causes a lot of them to be skipped).You also need to handle uppercase vowels as well, which can be checked more easily with a regular expression. Change the
if
statement in the first loop to:Finally, use
Array#join
with an empty string to get a string as the result.Move the count++
inside theif
:You could use
Array::unshift()
to collect the vowels already in a reversed order: