Intermediate Algorithm - Diff Two Arrays - Logical Operators

Tell us what’s happening:
I have passed this challenge with the code below. Now, I just wanted to test and try out the code below by replacing the || OR operator with the && AND operator to see what results can be yielded from it by invoking diffArray([1, 2, 3, 5, 6], [1, 2, 3, 4, 5]) in particular.

1. arr1.includes(x) || !arr2.includes(x)
For || OR operator, it returns [ 6, 4 ]. From my understanding, if either Condition 1 OR Condition 2, or both, is true, the filter method will evaluate, overall, that it is true and return the true value(s). Thus, even if one condition is false but the other is true, the filter method will evaluate, overall, it is true and return the value(s).

2. arr1.includes(x) && !arr2.includes(x)
However, for && AND operator, it returns an empty array []. Why is this the case? Shouldn’t this only happen when the filter method evaluates that, overall, it is false if one or both condition(s) is false and, thus, returns an empty array.

From my understanding, in this case, both Condition 1 AND Condition 2 are true, in which the filter method should determine that, overall, it is true and return [ 6, 4 ]. Is this right? Am I missing something? :frowning:

  **Your code so far**

function diffArray(arr1, arr2) {
return arr1.concat(arr2).filter(x => !arr1.includes(x) || !arr2.includes(x))
}

console.log(diffArray([1, 2, 3, 5, 6], [1, 2, 3, 4, 5]));

Challenge: Diff Two Arrays

Link to the challenge:

Quick refresher:
expr 1 && expr2 if expr1 is ture return expr2 , else return expr1.

expr1 || expr2 if expr1 is true returns it, else return expr2.

For a more detailed explanation refers to MDN.

In practice let’s take 4 as your filter arguments.
Also remember that you are negating the predicate of the includes fn with a !.

So you can read:

arr1 NOT INCLUDE 4 || arr2 NOT INCLUDE 4
arr1 NOT INCLUDE 4 && arr2 NOT INCLUDE 4

So they can be read as

true || false
true && false

Refers to the expression mentioned above you have

true -> kept in the final array
false -> removed from the final array

Hence in the former you get [4,6] while in the latter []

Hope this clarifies it a bit :sparkles:

1 Like

Awesome! Initially, I was very confused with the first two statements (about the expr1 and expr2) that were also present on MDN. I’ve done more in-depth reading on the logical operators, and solved some misconceptions, and, now, I fully understood your direct yet clear explanation! Thanks Marmiz!! :grin:

1 Like

Happens to forget the meaning and returns of those logical comparison.
What I generally do in those cases is opening the node repl, or just go into the browser console and start typing the possible permutations of true and false and the comparison.

That way you see immediately what will be the outcome.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.