Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While loop to print vowels and other elements on a new line in JavaScript

Trying to print any vowels from a word on a new line in the order they appear. Then do the same for each constant after all the vowels have been printed.

I've tried using breaks and a switch case but the code wouldn't work.

function vowelsAndConsonants(s) {
    var atom = s.length;
    var i = 0;
    while (i <= atom)
    {
        if (s[i] === 'a' || s[i] === 'e' || s[i] === 'i' || s[i] === 'o' || s[i] === 'u') {
            console.log('\n' + s[i]);
        }
        else {
            console.log('\n' + s);
        }
    }

}

I expect an output to be like:

a
i
o

Then the consonants in the order they appear:

t
p
r
like image 691
pikes_coffee Avatar asked Jan 23 '26 20:01

pikes_coffee


2 Answers

You can use includes to check vowel array on given string

const vowelsAndconsonants = str => {
  const vowels=['a','e','i','o','u'];
  //convert string to array and get rid of non alphabets as we are just interested on consonants and vowel
  const str_array=str.replace(/[^a-zA-Z]/g, '').split('');
  //pluck vowels
  const vowels_final=str_array.filter( a => vowels.includes(a.toLowerCase()));
  //pluck consonants
  const consonant_final=str_array.filter( a => !vowels.includes(a.toLowerCase()));
//to print any vowels from a word on a new line and then consonant in the order they appear. 
  return vowels_final.join('\n') + '\n' + consonant_final.join('\n');
}

console.log(vowelsAndconsonants('tEstOnlY and nothing else'))
console.log(vowelsAndconsonants('dry'))
console.log(vowelsAndconsonants('I love stackoverflow'))
like image 93
sumit Avatar answered Jan 25 '26 09:01

sumit


function vowelsAndConsonants(s) {
    let vowels = [];
    let consonas = [];
    for(var i=0; i<s.length ; i++) {
        if((s[i]=='a')||(s[i]=='e')||(s[i]=='i')||(s[i]=='o')||(s[i]=='u')){
            vowels.push(s[i])
        } else {
            consonas.push(s[i]);
        }
    }
    
    let concatArr = [...vowels, ...consonas];
    for (let i of concatArr) {
        console.log(i);
    }
} 
like image 40
Andrei Mocanu Avatar answered Jan 25 '26 10:01

Andrei Mocanu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!