Confused with result of IF STATEMENT

Confused with result of IF STATEMENT
0.0 0

#1

I am having trouble understanding the result of this code:

function diffArray(arr1, arr2) {
   var newArr = []; 


   var ordArr = arr1.concat(arr2).sort();   //[1,1,2,2,3,3,4,5,5]

   for(var i=0; i<ordArr.length; i++) {
       if(ordArr[i] !== ordArr[i+1]  &&  ordArr[i] !== ordArr[i-1]){
       newArr.push(ordArr[i]);
       }
   }

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

The result is [4] . But how I understand it, I always come up with [1,2,3,4,5] as the answer.

Here is how I interpret the if statement.

  1. if ordArr is not equal to the value of ordArr[i+1] and ordArr[i] is not equal to the value
    of ordArr[i-1] then push the current value of the current ordArr to the newArr.

So.

ordArr[i] !== ordArr[i+1]
result is [1,2,3,4,5]

and

ordArr[i] !== ordArr[i-1]
result is [1,2,3,4,5]

then newArr should be

[1,2,3,4,5]

But why is the result only [4] . How does && affect the result?


#2

Ah, so this time you’re saying:

if the current value is not the same as the next value and the current value is not the same as the previous value, only then will the value push to the new array.

Both of those have to be true to push (both sides of the &&):

[ 1 // same as next, so condition is false
, 1 // same as previous, so condition is false
, 2 // same as next, so condition is false
, 2 // same as previous, so condition is false
. 3 // same as next, so condition is false
, 3 // same as previous, so condition is false
, 4 // not the same as next, and not the same as previous, so condition is true
, 5 // same as next, so condition is false
, 5 // same as previous, so condition is false
]

Edit:

So, boolean logic -

  • AND: x && y is true if both x AND y are true
  • OR: x || y is true if either x OR y is true (both can be true, it checks x first, then y).
  • NOT: !x is true if x is false and is false if x is true

JS will convert anything in the brackets of the if statement it to a boolean value (true or false) so that you can do those comparisons. This means you have to be a little bit careful and make sure that the values you plug into it are actually what you want - numbers are the obvious one (0 or -0 are false, any other number is true)


#3

that’s exactly what happens: 4 is the only number in there that is different from both the number before and the one after.


#4

You don’t need to compare the current ordArr[i] with both preceding and the next just with the next ordArr[i+1] if they are the same you just loop and pass to the next. you make again the evaluation and if ordArr[i] !== ordArr[i+1] you just push the actual value of ordArr[i] into newArr. and so on.


#5

Thanks for this explanation. I compared ordArr[i+1] , ordArr[i] , ordArr[i-1] and saw what I’m missing.

I finally understand how it all works. A BIG THANK YOU! once again.