pikes_coffee
pikes_coffee

Reputation: 23

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

Upvotes: 1

Views: 14514

Answers (15)

ARHAM RUMI
ARHAM RUMI

Reputation: 543

This question is already answered well. You can also use for of loops.

function vowelsAndConsonants(s) {
  const vowels = [];
  const consonants = [];

  // Separating Vowels and Consonants
  for (let ch of s) {
    if ((ch == 'a') || (ch == 'e') || (ch == 'i') || (ch == 'o') || (ch == 'u')) {
      vowels.push(ch)
    } else {
      consonants.push(ch)
    }
  }

  // Printing only Vowels
  for (let v of vowels) {
    console.log(v)
  }

  // Printing only Consonants
  for (let c of consonants) {
    console.log(c)
  }
}

vowelsAndConsonants("astrononaut");

Upvotes: 0

D Study
D Study

Reputation: 1

function seprateVowelsConsonant(s = "javaScript") {
  let v = "";
  let c = ""
  for (const x of s) {
    if ('aioue'.includes(x)) {
      v += x + "\n";
    } else {
      c += x + "\n";
    }
  }
  console.log(v + c);
}

seprateVowelsConsonant();

Upvotes: 0

pikes_coffee
pikes_coffee

Reputation: 23

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'));
}

vowelsAndConsonants("test");
vowelsAndConsonants("astronaut");

Upvotes: 1

Asplund
Asplund

Reputation: 2486

I know I'm late but the accepted answer is really bad, this is not a hard problem and the other answers overcomplicated things way too much.

The most natural and simple solution is to match the vowels and the consonants separately then print them:

function printLetters(input) {
  const vowels = input.match(/[aieou]/gi);
  const consonants = input.match(/[b-df-hj-np-tv-z]/gi);

  console.log(vowels.join("\n"));
  console.log(consonants.join("\n"));
}

printLetters("stop overcomplicating things.");

Upvotes: 0

Dennis
Dennis

Reputation: 177

function vowelsAndConsonants(s) {
        const vowel = ['a','e','i','o','u'];
        let ourVowel = [];
        let ourConsonant = [];
    for(let i = 0; i < s.length; i++){
        if(vowel.includes(s[i].toLowerCase())){
            ourVowel.push(s[i]);
        }else{
            ourConsonant.push(s[i]);
        }
    }
    ourVowel.forEach(e=>{
        console.log(e);
    });
    ourConsonant.forEach(e=>{
        console.log(e)
    })
}

Upvotes: 0

Shubham
Shubham

Reputation: 1

function vowelsAndConsonants(s) {
  var a = s.length;
  for (var i = 0; i < a; i++) {
    if (s[i] == 'a' || s[i] == 'e' || s[i] === 'i' || s[i] == 'o' || s[i] == 'u') {
      console.log(`${s[i]}`);
    }

  }

  for (var j = 0; j < a; j++) {
    if (s[j] == 'a' || s[j] == 'e' || s[j] === 'i' || s[j] == 'o' || s[j] == 'u') {

    } else {
      console.log(`${s[j]}`)
    }
  }
}

vowelsAndConsonants('function')

Upvotes: 0

Andrei Mocanu
Andrei Mocanu

Reputation: 31

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);
    }
} 

Upvotes: 2

Shivananda Sai
Shivananda Sai

Reputation: 1

HackerRank Day 2: Loops

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

Upvotes: 0

Tonmoy Roy
Tonmoy Roy

Reputation: 1

We can solve the problem using the below codes too. [ Hackerrank Day2 Solution ]

function vowelsAndConsonants(s) {
    // Create an array of vowels
    const vowels = ['a','e','i','o','u'];
    // Split up the String and Convert it to an Array
    const letters = s.split('');
    // Check for vowels
    for(let i in letters){
        if(vowels.includes(letters[i])){
            // Print vowels on a new line for each characters.
            console.log(letters[i]);
        }
    }
    // Check for consonants
    for(let i in letters){
        if(!(vowels.includes(letters[i]))){
            // Print consonants on a new line for each characters.
            console.log(letters[i]);
        }
    }
}
const test = "javascript";
vowelsAndConsonants(test);

Upvotes: 0

Jyoti
Jyoti

Reputation: 21

visit: https://www.w3schools.com/code/tryit.asp?filename=GQP0X4ZZEKNQ for finding result in better way.

With the help of bellow we can separates vowels and consonants with the easy way

  let strOne = "javascriptloopsAI";  // take any string

  //String convert into lower case
 var str = strOne.toLowerCase();  
let vowelarr = ['a','e','i','o','u'];  //  use vowels array

 //  here's we are splitting str string with space.
let strArr = [...str];  

var html='';
var htmlV='';

//for loop for strArr 
for (i = 0; i < strArr.length; i++)
{
   let field='';
   //for loop for vowelarr 
   for (j = 0; j < vowelarr.length; j++)
   {
      if(strArr[i]==vowelarr[j])
      {
          field=strArr[i];
          htmlV += strArr[i]+'</br>'  // adding only vowels in htmlv variable
      }
   
    }
    if(strArr[i]!=field)
    {
      html += strArr[i]+'</br>'    //adding only  consonants in htmlv variable
    }
}
document.getElementById("demo").innerHTML = htmlV;  
document.getElementById("demo1").innerHTML = html;
<p id="demo"></p>
<p id="demo1"></p>

Upvotes: 1

Punyai Athwale
Punyai Athwale

Reputation: 39

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

Upvotes: 0

Grant Fortune
Grant Fortune

Reputation: 1

Hackerrank Day2 Solution:

function vowelsAndConsonants(s) {
//Create Array of vowels
   const vowels = ["a","e","i","o","u"];
//Convert String to Array
   const arr = s.split("");
//Empty vowels and cons array
   var vowelsFound = [];
   var cons = [];
//Push vowels and cons to their arrays
   for (var i in arr) {
     if (vowels.includes(arr[i])) {
        vowelsFound.push(arr[i]);
        } else {
            cons.push(arr[i]);
        }
   }
//ConsoleLog so that they in order and cons follows vowels on new lines
   console.log(vowelsFound.join('\n') + '\n' + cons.join('\n'))
}
//Test, Exclude in copy
vowelsAndConsonants(javascriptloops); 

Upvotes: 0

Rishu Ranjan
Rishu Ranjan

Reputation: 574

We can simply do this using regular expression to match vowels and consonants, and then print each of them.

Below is the working code snippet:

        function vowelsAndConsonants(s) {
            var vw =s.match(/[aeiouAEIOU]+?/g); //regular expression to match vowels
            var con=s.match(/[^aeiouAEIOU]+?/g); //regular expression to not match vowels, ie. to match consonants
            printOnConsole(vw); //print vowels
            printOnConsole(con); //print consonants
       }

      //function to print values on console.
       function printOnConsole(arrPrint){
         for(var i=0;i<arrPrint.length;i++){
            console.log(arrPrint[i]);
          } 
       }

Upvotes: -1

sumit
sumit

Reputation: 15464

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'))

Upvotes: 2

Dash
Dash

Reputation: 138

Your main problem is that you are deciding wether or not you should print when checking each letter. The result output for that would actually be initial string.

While sumit's answer does the trick, this is the way I would do it, since it requires you to loop through the letters only once:

const vowelsAndConsonants = (str) => {
    const vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'];
    // Check for vowels

    var letters = str.split('');
    var vowelsFound = [], consonantsFound = [];

    for (var i in letters) {
        if (vowels.includes(letters[i])) {
            vowelsFound.push(letters[i]);
        } else {
            consonantsFound.push(letters[i]);
        }
    }
    
    console.log("Vowels:", vowelsFound.join(""));
    console.log("Consonants:", consonantsFound.join(""));    
}

var str = "ThisIsATest";
vowelsAndConsonants(str);

Upvotes: 1

Related Questions