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

Tags: ,



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

Answer

So here is the final code that I used. Thank for the help Dash and summit. I combined both of their codes.

// This is the function with the parameter which will have the input.

    function vowelsAndConsonants(s) {

// This lists, all the vowels. Since I know the input is all lowercase, there is no need for uppercase. A lowercase method could also be used.

    const vowels = ['a', 'e', 'i', 'o', 'u'];

// The input is split up to avoid printing the entire string, and is stored in a variable.

    var letters = s.split('');

// An array to hold the vowels is created.

    var vowelsFound = [];

// An array to hold the consonants is created.

    var consonantsFound = [];


// Loops through all the split up characters held in the letters variable.

    for (var i in letters) {

// If statement tests by using include to see if any of vowels match the i looper.

        if (vowels.includes(letters[i])) {

//If any vowels do match, then they get added to the end of the vowelsFound array,

which then get pushed up, so that it can be printed in the order they appear.

            vowelsFound.push(letters[i]);

//The same process is used for the consonants.

        } else {
            consonantsFound.push(letters[i]);
        }
    }

//Prints the vowels in their order, on a new line for each character.

    console.log(vowelsFound.join('n'));
    console.log(consonantsFound.join('n'));
}


Source: stackoverflow