-1

I am having an issue here with getting my data. So I want to filter out any that has an invoice_status of "Draft" or "Ready to Bill", or "Cancelled" or if it's invoice_status is null AND status is null

Everything is being filtered out correctly except any data that has both invoice_status is null AND status is null is not being filtered out. What is the issue with my code below?

console.log(
  "data...",
  this.props.partnerOrders.filter(
    r =>
      (r.invoice_status !== "Draft" &&
      r.invoice_status !== "Ready to Bill" &&
      r.invoice_status !== "Cancelled") || 
      (r.invoice_status !== null && r.status !== null)
  )
);
Dave Smith
  • 21
  • 3
  • The `||` means that if the `invoice_status` check in the first part is true, the check for `null`s in the second part won't be performed at all. If you want to keep the entries that 1) Have `invoice_status` **not** equal to `Draft`, `Ready to bill`, or `Cancelled`, AND 2) Have `invoice_status` not `null` and `status` not `null`, you need to use `&&` instead of `||`. You literally just need a series of `!==` conditions joined by `&&`. – T.J. Crowder Jan 11 '22 at 15:14
  • Related: https://stackoverflow.com/questions/26337003/why-does-non-equality-check-of-one-variable-against-many-values-always-return-tr – T.J. Crowder Jan 11 '22 at 15:15
  • I have tried that too but it still doesn't work. It will filter everything out – Dave Smith Jan 11 '22 at 15:17
  • Please update the question with an array that has both entries you want to keep and ones you want to remove, and show us what the result array should look like. It sounds like the `status` check may need to be grouped in some way. (Are there entries with `status = null` that you want to keep?) – T.J. Crowder Jan 11 '22 at 15:18

2 Answers2

1

Your filter condition in the code is written as the negation (opposite) of your condition-as-words, so as to be true when the element should be kept. Your statement is correctly negated except: !invoice_status is null AND status is null is not (r.invoice_status !== null && r.status !== null), it is (r.invoice_status !== null || r.status !== null).

This is a general rule: !(A && B) == (!A || !B), see rules of negation.

MyStackRunnethOver
  • 4,872
  • 2
  • 28
  • 42
0

Since you want to filter out invoice_status is null AND status is null, when you invert the logic, by deMorgan's theorem, you get invoice_status is not null OR status is not null. Changing your final && to an || should do the trick

  • Actually I had to change something else too. The last && changed it to || and the last || changed it to && so it ended up looking like this ... && r.invoice_status !== "Cancelled" && (r.invoice_status !== null || r.status !== null)` – Dave Smith Jan 11 '22 at 15:33