-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverseVowels.js
48 lines (38 loc) · 1.08 KB
/
ReverseVowels.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
var reverseVowels = function (s) {
const vowels = ["a", "e", "i", "o", "u","A","E","I","O","U"];
let vowelArray = [];
for (let i = 0; i < s.length; i++) {
if (vowels.includes(s[i])) {
vowelArray.push(s[i]);
}
}
vowelArray.reverse();
let reversed = "";
let vowelIndex = 0;
for (let i = 0; i < s.length; i++) {
if (vowels.includes(s[i])) {
reversed += vowelArray[vowelIndex];
vowelIndex++;
} else {
reversed += s[i];
}
}
return reversed;
};
//Example 2
const reverseVowels = (s) => {
const vowels = new Set(["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]);
// Array.from('foo');
// [ "f", "o", "o" ]
const vowelArray = Array.from(s).filter((char) => vowels.has(char)); //a from converts into array of strings
vowelArray.reverse();
return Array.from(s).reduce((acc, char) => {
if (vowels.has(char)) {
acc += vowelArray.pop();
} else {
acc += char;
}
return acc;
}, "");
};
console.log(reverseVowels("hello"));