-1
wordArr = ['a', 'g', 'e', 'f'];
wordArr = wordArr.filter(function(l){
            return l !== 'a' || l!== 'e'|| l!== 'i'|| l!== 'o' || l!== 'u'; 
       });

My result: my wordArr doesnt change

Desire output: ['g', f'];

it only works with one condition, if i only check for one vowel. How do i make this work for multiple conditions?

thank you in advanced.

solid_soap
  • 55
  • 1
  • 10
  • Related: [Javascript filter check for multiple values?](https://stackoverflow.com/a/37807845/8289918) [How to Filter on multiple strings in JS?](https://stackoverflow.com/a/52909487/8289918) [how to filter multiple values from an array in javascript](https://stackoverflow.com/a/68100851/8289918) It's almost the same as your situation except you would use e.g. `!invalid.includes(l)` instead of `invalid.includes(l)` for example – Lauren Yim Aug 10 '21 at 00:30

2 Answers2

6

Your conditions are incorrect. Consider just the following:

return l !== 'a' || l!== 'e'

If the string (inside l) is foo, the result is true since it's not 'a'.

If the string is 'a', the result is true since it's not 'e':

return l !== 'a' || l!== 'e'
return false || true
return true

If the string is 'e', the result is true since it's not 'a':

return l !== 'a' || l!== 'e'
return true || false
return true

You need &&s instead.

return l !== 'a' && l!== 'e'&& l!== 'i'&& l!== 'o' && l!== 'u'; 

Or, even better:

const wordArr = ['a', 'g', 'e', 'f'];
console.log(wordArr.filter(str => !/[aeiou]/.test(str)));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • 1
    I'd be interested to see what's faster; `RegExp.prototype.test()` or `Set.prototype.has()` – Phil Aug 10 '21 at 00:32
  • wow thank you for such an in depth response and explanation! I see where my logic went wrong after this thank you! just starting to learn programming so this has been really helpful – solid_soap Aug 10 '21 at 00:35
  • If you want to filter out uppercase vowels as well with the regex, you could use `/[aeiou]/i` – Lauren Yim Aug 10 '21 at 00:37
2

You are using || here which will check for either of the condition that causing the problem. Just use && instead of ||

wordArr = ["a", "g", "e", "f"];
const result = wordArr.filter(function(l) {
  return l !== "a" && l !== "e" && l !== "i" && l !== "o" && l !== "u";
});

console.log(result);

Alternatively, you can use includes to check for existence.

const wordArr = ["a", "g", "e", "f"];
const vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"];

const result = wordArr.filter((l) => !vowels.includes(l));

console.log(result);
DecPK
  • 24,537
  • 6
  • 26
  • 42