This is my code thus far, it duplicates vowels e.g.:
baloona,o,oa,oHow can I fix this?
function printOutVowels(str) {
let vowels = "";
for (let i = 0; i < str.length; i++) {
if (str[i] == "a" || str[i] == "e" || str[i] == "i" || str[i] == "o" || str[i] == "u") {
vowels = str[i]
console.log(vowels);
}
}
}
printOutVowels("timidity");
One solution is using Set data structure. A set is like an array, but contains no duplicated element.
function printOutVowels(str) {
// Create an empty set
const vowels = new Set();
for (let i = 0; i < str.length; i++) {
if (str[i] == "a" || str[i] == "e" || str[i] == "i" || str[i] == "o" || str[i] == "u") {
// Add element to the set
vowels.add(str[i]);
}
}
// Print the set content
for (let item of vowels) {
console.log(item);
}
}
printOutVowels("timidity");
Behind the scene, Set use its has method to check if an item is already in the set. This method is faster than Array.prototype.includes when a set and an array have the same size.
You could do that :
function printOutVowels(str){
let vowels = "aeiou";
let output = "";
for (let i = 0; i < vowels.length; i++) {
if(str.toLowerCase().includes(vowels[i])) output += vowels[i];
}
return output;
}
Splitting and filtering is a concise way to get the vowels. Running them through a set will enforce uniqueness. (Force to lowercase to handle both cases)
function vowels(str) {
const isVowel = l => /^[aeiou]$/.test(l);
const vowels = new Set(str.toLowerCase().split('').filter(isVowel));
return Array.from(vowels.values());
}
console.log(vowels('TIMidity'))