Diff-two-arrays(can't debug non-working algorithm)

Challenge: challenges/diff-two-arrays

function diffArray(arr1, arr2) {
  var newArr = [];
  // Same, same; but different.//JF
  console.log("arr1: " + arr1 + "   arr2: " + arr2);
  
  for ( var i = 0; i < arr1.length; i++ ){
    
    var oldLength;
    oldLength = arr2.length;
    arr2=arr2.filter(filterer, arr1[i]);
    if ( arr2.length !== oldLength)
      arr1[i] = null;
    
  }
  
  
  arr1=arr1.filter(filterer, null);
  console.log("second----- arr1: " + arr1 + "   arr2: " + arr2);
  return arr1.concat(arr2);
}

function filterer(value){
  
  if ( this !== value )
    return true;
    
}

diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);

A good first step is to add in hella console.log() statements to identify where things aren’t what you expect them to be (when you’re developing a full project you’ll use debugging with breakpoints to accomplish this).
Here is a link to your code with more logging.

Now we can see that the problem is that both this and value have the type of object. With objects, I believe that strict equality requires the two objects to have the same reference (they are two variable names referring to the same object) as opposed to by value.
Here is a link to your code without strict inequality.

Now we can see that there is still a problem with your approach: instead of returning the array ['pink wool'] we have an array where all the duplicated values are replaced with null.
I’ll leave you to look for the logic error that is causing that problem.

Happy coding!

2 Likes

+1 to the console.log love. I’m just now starting to learn testing, but I’m all about putting console.log all over when I’m trying to figure out what’s going wrong.

Very good explanation, and for learning purpose “abstract” :slight_smile:

I have read here: https://www.toptal.com/javascript/10-most-common-javascript-mistakes

this: “(== and != automatically perform type conversion when comparing two things, whereas === and !== do the same comparison without type conversion.)”.

I’m not sure yet why i need to use “!=” instead “!==”? When, this is digit as, value in filterer?

It’s because we’re looking at objects.
Here is a link to your code with this and value converted to strings before comparison.

As per MDN’s page on Comparison operators:

Two distinct objects are never equal for either strict or abstract comparisons.

1 Like

Can u explain me this code:

  var a1 = ["yes"];
  var a2 = ["yes"];
  
  var a3 = ["yes", "yes"];

  return a3[0] === a3[1]; // return true
  return a1[0] === a2[1]; // return false

You have an error. a2[1] is undefined.

  var a1 = ["yes"];
  var a2 = ["yes"];
  
  var a3 = ["yes", "yes"];
  
  console.log("a1[0]" + ": " + a1[0] + ": " + typeof a1[0]); // a1[0]: yes: string
  console.log("a2[1]" + ": " + a2[1] + ": " +typeof a2[1]); //a2[1]: undefined: undefined

  console.log(a1[0] === a2[1]); // false - because "yes" !== undefined
2 Likes