• [deleted]
    + 10 comments

    I did it like this. How good it is?

    function vowelsAndConsonants(s) {
        let vowels = ["a", "e", "i", "o", "u"];
    
        for(let v of s) {
            if(vowels.includes(v))
                console.log(v);
        }
        
        for(let v of s) {
            if(!vowels.includes(v))
                console.log(v);
        }
    }
    
    • + 7 comments

      You're looping through the input string twice, doing the same thing, which breaks a very important rule in programming - DRY (don't repeat yourself). My advice is to try to produce a respone by looping only once through s, which will require vowels to be presented in more efficient way (the problem does not state they have to be stored in an array).

      • + 2 comments

        This According to me is very trivial requirement. Although it violates DRY. Asymptotically it does not make difference at all. And if efficiency were an aspect, in some way one could argue that concurrency(which is generally required for large data) would be well implemented in two loops. without using DS like string to store data. (Also your solution may introduce an unecessary (worstcase)O(n) space complexity).

        • + 1 comment
          [deleted]
          • + 0 comments

            here is Loops problem solution in javascript https://solution.programmingoneonone.com/2020/06/hackerrank-day-2-loops-solution-javascript.html

        • + 0 comments

          For complete updated problem solution in javascript programming language https://programs.programmingoneonone.com/2021/02/hackerrank-day-2-loops-solution-javascript.html

      • + 12 comments

        The KISS beats DRY here:

        function vowelsAndConsonants(s) {
            [...s].forEach(c => 'aeiou'.includes(c) ?
                console.log(c) : null);
            [...s].forEach(c => 'aeiou'.includes(c) ?
                null : console.log(c));
        }
        
        • + 1 comment

          Its still 2 for loop right?

          • + 1 comment

            Yes.

            • + 0 comments

              please folow me

        • + 1 comment

          This returns unique characters only. Check it in your console. It will return the following: a i o j v s c r p t l p s

          • + 0 comments

            Idk if the ES versions have changed, but it works now

        • [deleted]
          + 1 comment

          can you kindly explain this for me. Thanks

          • + 1 comment

            [...s] can be decomposed in :

            ... : the spread operator (check the documentation)

            s : the string s

            [] : array symbol

            the spread operator will take each iterable of the string s (each character) and put it in an array.

            A forEach loop is used on that array, that will call a function for each of its items, in which the item is used as parameter.

            It could be writen as such :

            array.forEach(function(character) = { function });

            That function will check if the character is included in the provided string of vowels, and return the value or not using the ternary operator.

            if (character == vowel) { return character } else { return null }

            can be writen like that :

            return character == vowel ? character : null

            I hope this can help anybody.

            • + 0 comments

              Much better when someone explain. Thank you

        • + 0 comments

          I don't know why people downvoted your answer. It's quite stylish with these spread and ternary operators, and who cares if it loops through the string twice, this means nothing performance-wise, it's much better to have readable code.

        • + 0 comments

          Nice one

        • + 0 comments

          what about similar approach, but looping only once through string, but again through array?

          function vowelsAndConsonants(s) {

          let vowels = [], consonants = [];

          [...s].forEach(current => 'aeiou'.includes(current) ? vowels.push(current):consonants.push(current));

          for (let element of vowels) { console.log(element); } for (let element of consonants) { console.log(element); } }

        • + 1 comment

          For DRY believers:

          function vowelsAndConsonants(s) {
              var consonants = '';
              [...s].forEach(c => 'aeiou'.includes(c) ?
                  console.log(c) : consonants += c + '\n');
              console.log(consonants);
          }
          
          • + 0 comments

            This solution is much more better in terms of timecomplexity

        • + 0 comments

          Giving a dislike coz it seems difficult for beginners.

        • + 0 comments

          Not sure why this has been so downvoted. The use of two for loops is meaningless. Doesn't add much of a speed hit at all.

        • + 0 comments

          Would you like to explain your code

      • + 0 comments

        see mine, lol.

        function vowelsAndConsonants(s) {
            const consonants = []
            const vowels = {a: 1, e: 1, i: 1, o: 1, u: 1}
            // print vowels
            s.split('').map((char) =>
                vowels[char] ? console.log(char) : consonants.push(char)
            )
            
            // print consonants
            consonants.map((consonant) => console.log(consonant))
        }
        
    • + 51 comments

      looping only once:

      function vowelsAndConsonants(s) {
          const vowels = 'aeiou';
          var consonants = '';
          
          for(var i = 0; i < s.length; i++) {
             if (vowels.includes(s[i])) {
                 console.log(s[i]);
             }
             else {
                 consonants += s[i] + '\n';
             }
          }
          
          console.log(consonants.trim());
      }
      
      • + 2 comments

        Brilliant answer loved it

        • + 0 comments

          Actually, the includes method loops through vowels. So you're looping through the parameter string "s" and vowels too.

      • + 0 comments

        brilliant...

      • + 2 comments

        Sorry for my language but this is the sexiest answer

        • + 0 comments

          ✔ you correct

        • + 3 comments

          Put some tan on, using turnary operator :)

              let consonants = ''
              let vowels = 'aeiou';
              for (let letter of s) {
                  vowels.includes(letter) ? console.log(letter) : consonants += letter + '\n';
              }
              console.log(consonants.trim());
          }
          
          • + 0 comments

            best thanks!

          • + 0 comments

            Nice solution!

          • + 1 comment

            could you explain this for me

            • + 1 comment
                  vowels.includes(letter) ? console.log(letter) : consonants += letter + '\n';
              

              Here is the "ternary" operator. The '?' says if this thing before the ?, do the thing right after the ?, else do the thing right after the :. It is a shortcut for the if statement. The statement reads: If the letter is found in the vowels, (log it), else add it to the list of consonants with a new line (This is the loop) to be logged in the final console log of consonants without whitespace. } console.log(consonants.trim()); }

      • + 0 comments

        Sneaky sneaky :D

      • + 2 comments

        Correct me if I'm wrong but isnt the complexity of .includes() of O(n)? So technically its not looping once.

        • + 0 comments

          Can be fixed with RegEx /[aeiou]/.test(s[i])

          Although I am fairly sure the complexity of .includes() depends on the array the method is called on, which in this case is small and constant (it's just the 5 vowels).

        • + 1 comment

          Its not O(n) but O(5), which makes it trivial

          • + 0 comments

            Well, it's not O(n) in this case because we know how many letters there are.

      • + 1 comment

        works fine without trim()

        • + 0 comments

          It actually adds an extra line break at the end if you don't include trim().

      • + 1 comment

        how do you write it with code format?

        • + 0 comments

          click on this symbol while writting comment.

      • + 1 comment

        But still the complexity of the code remains same as o(n).

        Is there any solution with o(1).

        • [deleted]
          + 0 comments

          No, the amount of time has to be dependent on the input. The only way n(o) could happen is if you are doing a calculation not dependent on the length of the input( adition, lowest value, etc).

      • + 2 comments

        I did something similar in a one iteration, however I stored the consonents in an actual array whereas you used a string. Is my way less efficient. My reasoning is that behind the scenes I think that javascript is representing strings as an array. Therefore there should be no performance difference.

        function vowelsAndConsonants(s) {
            let consonents = [];
            for (let l in s){
                if ("aeiou".includes(s[l])){
                    console.log(s[l]);    
                }
                else {
                    consonents.push(s[l]);
                }
            }
            for (let nV in consonents){
                console.log(consonents[nV]);
            }
        }
        
        • + 0 comments

          I did some research on JavaScript string concatenation vs array performance-wise. My conclusion is that it depends.

          The reason is not what you suspected: virtually all programming languages represent strings as a character array, by definition.

        • + 0 comments

          The KISS beats DRY here:

          function vowelsAndConsonants(s) {
              [...s].forEach(c => 'aeiou'.includes(c) ?
                  console.log(c) : null);
              [...s].forEach(c => 'aeiou'.includes(c) ?
                  null : console.log(c));
          }
          
      • + 0 comments

        Awesome

      • + 0 comments

        Brillant answer.

      • + 1 comment

        Why is there a need to store the remaining letters in a var first at the else condition then console.log the var later? Is there a way to console.log the remaining letters right away in the else condition?

        • + 0 comments

          No, because you have to print out the vowels first. Everything in your else block is a consonant so you have to print those after the fact.

      • + 5 comments

        I had a fairly similar solution.

        function vowelsAndConsonants(s) {
            const vowels = "aeiou";
            var cons = "";
            for (let i = 0; i < s.length; i++) {
                vowels.includes(s[i]) ? console.log(s[i]) : cons = cons.concat(s[i] + '\n');
            }
            console.log(cons);
        }
        
        • + 0 comments

          Best , i guess ! :)

        • + 0 comments

          Ternary operation is best. kinda liked it

        • + 0 comments

          The quickest

        • + 0 comments

          The KISS beats DRY here:

          function vowelsAndConsonants(s) {
              [...s].forEach(c => 'aeiou'.includes(c) ?
                  console.log(c) : null);
              [...s].forEach(c => 'aeiou'.includes(c) ?
                  null : console.log(c));
          }
          
        • + 0 comments

          function vowelsAndConsonants(s) { let vowels = ["a", "e", "i", "o", "u"]; var others = ''

          for(let v of s) {
              if(vowels.includes(v)){
                  console.log(v);
              } else{
                  others += v + "\n"
              }
          }
          console.log(others)
          

          }

      • + 0 comments

        i am having trouble understanding your code. Would you be king enough to explain me ? i am a new student.

      • + 0 comments

        The most pleasing answer...

      • + 0 comments

        Here if we have vowels as String, and call includes method, each time there is an extra work of converting String to array to check if the data is present. So This is happening for N times.

      • + 0 comments

        thanks

      • + 2 comments

        Your wonderful solution may be compressed into a one-liner like this:

        const vowelsAndConsonants = s => { console.log(s.replace(/[aeiou]|/g, m => m ? console.log(m) || "" : "\n").trim()) };
        
        • + 0 comments

          The KISS beats DRY here:

          function vowelsAndConsonants(s) {
              [...s].forEach(c => 'aeiou'.includes(c) ?
                  console.log(c) : null);
              [...s].forEach(c => 'aeiou'.includes(c) ?
                  null : console.log(c));
          }
          
        • + 0 comments

          I learned a lot from this one. Thank you.

      • + 0 comments

        it doesnt run

      • + 0 comments

        why do you use trim()? you could just print the consonants, because you already have break-line

      • + 0 comments

        why are you using trim. Even if you don't use it this wil work.

      • + 1 comment
        [deleted]
        • + 0 comments

          It's not necessary to consider them because input strings are guaranteed to be lowercase:

          Complete the vowelsAndConsonants function in the editor below. It has one parameter, a string, s, consisting of lowercase English alphabetic letters (i.e., a through z).

      • + 0 comments

        That was genius...

      • + 3 comments

        Can anybody explain this part of the code: else { consonants += s[i] + '\n'; }

                 What means: + '\n';  
        
        • + 0 comments

          It means that it should be printed on a new line

        • + 0 comments

          A new line character. So everytime it will display new letter in new line.

        • + 0 comments

          Assign each loop index that's not vowel to a new line

      • + 0 comments

        Similar but used array:

        var arr = new Array(s.length); var j = 0; for (let 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 { arr[j] = s[i]; j++; } } for (let i of arr) { if(i!=undefined) console.log(i); }

      • + 1 comment

        The KISS beats DRY here:

        function vowelsAndConsonants(s) {
            [...s].forEach(c => 'aeiou'.includes(c) ?
                console.log(c) : null);
            [...s].forEach(c => 'aeiou'.includes(c) ?
                null : console.log(c));
        }
        
      • + 0 comments

        i solved mine quite similary

        function vowelsAndConsonants(s) {
            let vowels = ['a', 'e', 'i', 'o', 'u'];
            let consonants = [];
        
            for (let i = 0; i < s.length; i++) {
                if (vowels.includes(s.charAt(i))) {
                    console.log(s.charAt(i));
                } else {
                    consonants.push(s.charAt(i));
                }
            }
            consonants.forEach(val => console.log(val));
        }
        
      • + 0 comments

        Not sure if concatinating to plain string is memory efficient of Javascript string works like StringBuilder in other languages.

      • + 0 comments

        This is so beautiful.

      • + 0 comments

        Could you please explain the else part?

      • + 0 comments

        brilliant

      • + 0 comments

        only if you could do var len = s.length; and the use the variable in the for loop will save time. The program will not have to calculate the length eacch time if you do something like this.

      • + 0 comments

        \n is not working in consonants += s[i] + '\n';

        we could use
        in the place of \n

      • + 0 comments

        instead of string use an array:

        function vowelsAndConsonants(s) { const vovels = 'aeiou'; var consonents = []; var x; for(x in s){ if(vovels.includes(s[x])){ console.log(s[x]); } else{ consonents.push(s[x]); } }

        for(x in consonents) console.log(consonents[x])

        }
      • + 0 comments

        very smart answer.

      • + 0 comments

        nice idea

      • + 0 comments
        function vowelsAndConsonants(s) {
        const vowels = 'a,e,i,o,u';
        let consonants = '';
        for(let i=0; i < s.length; i++){
            vowels.includes(s[i]) ? console.log(s[i]) : consonants += s[i] + '\n';
        }
                console.log(consonants);       }
        
      • + 0 comments

        why did you use trim() function? not necessary

      • + 0 comments

        y is trim used can anybody explain

      • + 0 comments

        Thanks for the help ,the readability of code is commendable (without the trim function also it passes the testcases) .

      • + 0 comments

        This is a time-space complexity tradeoff.

        You do loop through only once, so you have O(n) time complexity rather than O(2n). That's still linear.

        However, by creating this consonants string, you're creating a variable that increases linearly in size with the size of input (worst case). That's O(n) space complexity.

      • + 0 comments

        for(var i = 0; i < s.length-1; i++) .. //s.length-1 will be required so as to avoid an undefined value being printed

      • + 0 comments

        that is what I need :D

      • + 0 comments

        why it's necessary to use .trim method?

      • + 0 comments

        instead of adding all the consonants to a seperarte variable is it not possible to simply remove the vowels (every time the 'if' loop is entered) from the original string and then print the original string itself instead of 'consonants'?

      • + 0 comments

        I am new to JS !! why did we use console.log(consonants.trim()); here ???

      • + 0 comments

        tanning a bit more

        let consonants = '' let vowels = 'aeiou'; [...s].forEach((letter) => { vowels.includes(letter) ? console.log(letter) : consonants += letter + '\n'; } ) console.log(consonants.trim());

      • + 0 comments

        Clever. Certainly very efficient. Perhaps a bit less readable than two loops however.

      • + 1 comment

        I'm a noob here. what is the consonants.trim do in this can anyone explain?

        • + 0 comments

          trim() removes whitespace from both ends of a string, so in this case it removes trailing newline \n from the consonants variable.

          More on String.prototype.trim() on MDN.

      • + 0 comments

        This is where trade of between memory and time complexity comes in Some people perefer looping twice(linear complexity) and some prefer making use of extra variables.

        Nicely Written code though.

    • + 1 comment

      NIce approach, but not sure if it would work without the if statements curly braces.

      • + 1 comment

        Curly braces are optional for single statements (MDN if syntax), so a line of code below will speak for itself.

        if (true) console.log('It works!');
        

        Nevertheless, it is considered to be a good practice to turn single statements into block statements by using curly braces around them.

        • + 0 comments

          Thanks for your response, i never used it that way, but i use arrow functions that way if its returning a single statement. Thanks for the heads up. Yeah it sure is a good practice to include the curly braces.

    • + 0 comments

      Try to avoid the "includes" method. You will find yourself running into road blocks when creating apps for internet explorer. I would recommend indexOf() which is recognized by IE and all modern browsers.

    • + 0 comments
      function vowelsAndConsonants(s) {
          
          for(let i=0; i<s.length; i++)
          {
              if("aeiou".includes(s[i]))
              console.log(s[i]);
      
          }
      
          for(let i=0; i<s.length; i++)
          {
              if( !("aeiou".includes(s[i])))
              console.log(s[i]);
              
          }
      }
      
    • + 0 comments

      it was Arsom

    • + 0 comments

      Thanks Man for this answer i was so confused but once i see this answer i remove all my worries

    • + 1 comment

      function vowelsAndConsonants(s) { for(var i=0;i } } for(var i=0;i

      }
      

      }}

      • + 1 comment

        kalinga_abishek yes eat

        • + 0 comments

          if you want download app download app