'Checking for multiple conditions with JavaScript includes() method inside filter() method
I am trying to filter out words that include zz or ZZ but can't quite get it to work. I am trying to use includes() within the filter() method. I'm not sure if the || operand is the correct choice here.
function removeZZ (str){
let splitStr = str.split(" ")
let noBuzz = splitStr.filter(word => !word.includes("zz") ||!word.includes("ZZ") )
return noBuzz.join(" ")
}
Solution 1:[1]
You can use word.toLowerCase().includes
const str = "wed zzAA ZZSS 34f34f"
function removeZZ(str) {
return str
.split(" ")
.filter(word => !word.toLowerCase().includes("zz"))
.join(" ");
}
console.log(removeZZ(str))
With your approach you need to use && instead of ||
const str = "wed zzAA ZZSS 34f34f"
function removeZZ(str) {
let splitStr = str.split(" ")
let noBuzz = splitStr.filter(word => !word.includes("zz") && !word.includes("ZZ"))
return noBuzz.join(" ")
}
console.log(removeZZ(str))
Solution 2:[2]
Or simply you can make each word lowercase and check if it includes 'zz'. Try the following example.
function removeZZ (str){
let splitStr = str.split(" ")
let noBuzz = splitStr.filter(word => !word.toLowercase().include('zz'))
return noBuzz.join(" ")
}
Solution 3:[3]
Your logic is a bit inverted by using the || instead of && operator.
Instead you could write this:
let noBuzz = splitStr.filter(word => !word.includes("zz") && !word.includes("ZZ") )
Or use an Array of blocked words instead:
let noBuzz = splitStr.filter(word => !["zz", "ZZ"].includes(word))
Or, as they are the same and only the case is different, try a Regex:
let noBuzz = splitStr.filter(word => !word.match(/zz/i))
Solution 4:[4]
Here is code , hope it will help you. Your First error is you are not returning anything from filter method. Second error is in or (||) condition. You have to use and (&&) condition for checking both conditions if word not contains 'zz' and 'ZZ'.
function removeZZ (str){
let splitStr = str.split(" ")
let noBuzz = splitStr.filter(word =>{
if(!word.includes("zz") && !word.includes("ZZ")){
return word;
}
})
return noBuzz.join(" ")
}
const ans=removeZZ("zz asoaZZzz aos as ZZAas Azz");
console.log("ans is : ",ans)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Exonnix Kai |
| Solution 3 | James Hooper |
| Solution 4 | Poojan3037 |
