I am trying to extract some vowels from an array using the .filte() method but the code doesn't continue on the next letters after finding instances of the first letter.The expected output is ['a','a','i'] but it only shows ['a','a'] Here is the code
function vowelsAndConsonants(s) {
const letters = s.toString().split("");
console.log(letters);
let vowels = letters.filter((letter) => {
return letter.includes("a", "e", "i", "o", "u");
});
console.log(vowels);
}
vowelsAndConsonants("javascript");
CodePudding user response:
Here's one way of getting the vowels
function vowelsAndConsonants(s) {
const letters = s.toString().split("");
let vowels = letters.filter((letter) => {
return ['a', 'e', 'i', 'o', 'u'].indexOf(letter) !== -1
});
console.log(vowels);
}
vowelsAndConsonants("javascript");
CodePudding user response:
The include method can only have one argument, see this website, the easiest way to test is by testing the value with an if :
const vowels = letters.filter((letter) => {
if (letter === "a" || letter === "e" || letter === "i" || letter === "o" || letter === "u" || letter === "y")
return (letter);
return("");
});
CodePudding user response:
You could also use Regular Expression.
function vowelsAndConsonants(s) {
const letters = s.toString().split("");
console.log(letters);
let vowels = letters.filter((letter) => {
return /[aeiou]/.test(letter);
});
console.log(vowels);
}
vowelsAndConsonants("javascript");
CodePudding user response:
Respecting your coding logic, I only fixed an issue with your includes
usage :)
const allVowels = ["a", "e", "i", "o", "u"]; // what about "y" ?
function vowelsAndConsonants(s) {
const letters = s.toString().split("");
console.log(letters);
let vowels = letters.filter((letter) => {
return allVowels.includes(letter);
});
console.log(vowels);
}
vowelsAndConsonants("javascript");
CodePudding user response:
You could reduce the letters into a Map
and store the occurrences with a Set
or an Array
([]
).
const VOWELS = new Set('aeiou'.split(''));
const __charType = (ch) =>
VOWELS.has(ch) ? 'vowels' : 'consonants';
const __resultTemplate = (unique = false) =>
new Map(Object.entries({
vowels: unique ? new Set() : [],
consonants: unique ? new Set() : []
}));
const vowelsAndConsonants = (str, unique = false) =>
str.toLowerCase().split('').reduce((acc, ch) =>
(key =>
acc.set(key, unique
? acc.get(key).add(ch)
: [...acc.get(key), ch]))
(__charType(ch)),
__resultTemplate(unique));
const test1 = vowelsAndConsonants('javascript');
console.log(`Vowels : ${[...test1.get('vowels')].join(', ')}`);
console.log(`Consonants : ${[...test1.get('consonants')].join(', ')}`);
const test2 = vowelsAndConsonants('javascript', true);
console.log(`Vowels : ${[...test2.get('vowels')].sort().join(', ')}`);
console.log(`Consonants : ${[...test2.get('consonants')].sort().join(', ')}`);