Javascript Filter Func: Filter On Multiple Conditions (either Could Be True)
Might be something super simple that I am over looking. I have an array of objects that contains some info. Based on user action, I'd like to filter out some objects; let arr = [
Solution 1:
Every single num
will pass either of your if
conditions because there isn't a number in the universe which is equal to 1 and 3 at the same time**. You can just chain the &&
condition inside the filter
to check for all of them:
let arr = [
{'num': 1, 'name': 'joe'},
{'num': 2, 'name': 'jane'},
{'num': 3, 'name': 'john'},
{'num': 3, 'name': 'johnny'},
]
let filtered = arr.filter(a => a.num && a.num !== 3 && a.num !== 1)
console.log(filtered)
(**Unless it's 0
, null
, undefined
or any of the falsy values of course. In which case they will fail the obj.num
condition of both if
s)
Solution 2:
Let's understand the problem first.
so you had two conditions one checks for not equal to 1
and other checks for not equal to 3
so for example if num = 1
first one fails but second one still pass so eventually you're returning true
in every case.
You need to check both the condition in single if statement.
let arr = [{'num': 1, 'name': 'joe'},{'num': 2, 'name': 'jane'},{'num': 3, 'name': 'john'},{'num': 3, 'name': 'johnny'},]
functionfilterArr(arr) {
return arr.filter(obj => obj.num !== 1 && obj.num!=3)
}
console.log(filterArr(arr))
Post a Comment for "Javascript Filter Func: Filter On Multiple Conditions (either Could Be True)"