Today I worked on HackerRank and completed day 0-1 and did some other ones for practice."
I feel really good about this problem, came up with a solution that I am very happy about.
The goal:
First, print each vowel in on a new line. The English vowels are a, e, i, o, and u, and each vowel must be printed in the same order as it appeared in.
Second, print each consonant (i.e., non-vowel) in on a new line in the same order as it appeared in.
example:
"devto"
should print like so:
e
o
d
v
t
The first thing I did was create an array let strArr=s.split('')
out of the string using .split('')
( @laurieontech
had a good topic on the called Splice! Slice! Shoot, I meant Shift!) then a few more, one for the vowel let v = []
and one for the consonants let c = []
.
next, I created a static array of just vowels
let vowels = ['a','e','i','o','u']
.
then, I did a forEach()
loop (goes through every item in the array) (set up like this: strArr.forEach(letter=>{})
'letter' representing each item), in the loop I checked if the vowels (vowels
) array includes the letter that we are on in the loop if(vowels.includes(letter))
if that was true I would push the 'letter' to a new vowel array (v
) and the consonants go into their own
array (c
). Lastly return it all in one array return [...v ...c].join('\n')
then .join('\n')
them all to one string creating a new line at every letter.
With it put together it looked like this:
function vowelsAndConsonants(s) {
let strArr = s.split('');
let vowels = ['a', 'e', 'i', 'o', 'u'];
let v = [];
let c =[];
strArr.forEach(letter => {
if (vowels.includes(letter)) {
v.push(letter);
} else {
c.push(letter);
}
})
return [...v, ...c].join('\n');
}
Top comments (0)