I have recently stumbeled upon a problem on Code wars that seems very simple but when I try to check if vowel is present it just return the original string. Help would be appreciated.
function disemvowel(str) {
let vowels = ['a', 'i', 'o', 'u', 'e'];
let strArray = str.split("");
strArray.forEach(letter => {
for(let i = 0; i < vowels.length; i++)
{
if(letter === vowels[i] || letter === vowels[i].toLowerCase() )
{
letter = "";
}
}
});
const string = strArray.join("");
return string;
}
I’ve tried to restructure the if statement but to no success.
3
Answers
When you edit your
letter
variable in theforEach
loop, you aren’t editing the letter in the array, but rather a copy of the letter that the function gave to you to iterate over. So in short, you are not able to edit the array in that manner. What you want to use instead is themap
function which is similar, but is different in a few ways.The
forEach
function will only loop over the array and run that callback function for each element in the array. This basically acts as another way to write a for loop.The
map
function will also do that but it expects the callback function to return a value which will be the new value of the element. However themap
function doesn’t directly edit the original array, but rather edits a copy of the array and returns that copy.Also, the vowels in your array are already in lowercase, and the second check in your if statement should be
vowels[i].toUpperCase()
. So your code should look like this:What you are looking for is something like this.
You don’t really need loops for this.
If you still want to stick to your approach with
forEach
and make it work, this could be done like shown below.In your code, you were trying to modify
letter
, which is a local variable within theforEach
loop, and hence assigning value to it doesn’t modify the original array. The code below usesresult
var to overcome this problem.The given problem is about omitting the vowels from string or simply replacing the vowels with blank