Generaldeep
Generaldeep

Reputation: 445

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 = [
 {'num': 1, 'name': 'joe'},
 {'num': 2, 'name': 'jane'},
 {'num': 3, 'name': 'john'},
 {'num': 3, 'name': 'johnny'},
]

what I've tried

 function filterArr(arr) {
  return arr.filter(obj => {
    if(obj.num && obj.num !== 1) {
      return obj;
    }
    if(obj.num && obj.num !== 3) {
     return obj;
    }
  })
}

when i run filterArr, I am returned back the original array, but the expected result should be just {'num': 2, 'name': 'jane'},,. I can console.log inside both of the nested condition.

Any help of filtering array based on 1 of 2 conditions being true would be appreciated.

Upvotes: 1

Views: 553

Answers (2)

adiga
adiga

Reputation: 35253

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 ifs)

Upvotes: 4

Code Maniac
Code Maniac

Reputation: 37755

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'},]

function filterArr(arr) {
  return arr.filter(obj => obj.num !== 1 && obj.num!=3)
}

console.log(filterArr(arr))

Upvotes: 2

Related Questions