Free Code Camp Intermediate Scripting: Diff Two Arrays

jackLyons Free Code Camp Tags:
0

This seemingly simple Free Code Camp intermediate algorithm problem requires a bit of deeper thinking and understanding of functions, however it’s all there in the MDN JavaScript documentation. The question asks us to “Compare two arrays and return a new array with any items only found in one of the two given arrays, but not both. In other words, return the symmetric difference of the two arrays.

Take the first example test case below. Can you spot the difference?

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

As you can see, Array II has a 4 and Array I doesn’t. So, lets take a look at how to go about spotting the difference in JS.

How to solve the problem:

Step 1: Concatenate both arrays.

My thinking is simple. Why not just add both arrays together, then go about scanning the array for duplicates? You can use the very easy .concat() method for this. Be sure to store the result in a new variable, like newArr.

Step 2: Write a function to check both arrays.

This step is a little more complex as you need to write a function within the existing function. Of course, there are other ways of solving the problem that don’t require this particular strategy, however that’s totally up to you and what you understand. Anyhow, what I’m looking to do is to filter the array.

function search(num) {
  if (arr1.indexOf(num) === -1 || arr2.indexOf(num) === -1) {
    return num;
  }
}

If you don’t understand what the -1 means, please take a look at the indexOf() documentationThere, you will see that the method returns -1 if the value to search for never occurs. With the creation of this function, we can now pass it into the filter method which will take this function as an argument.

Step 3: Filter the newArray

So now we’re down to business. The filter method is awesome because you can write any sort of testing function and apply it. For example if you wanted to check if the users age was above 18, then you could write a simple function that only returns numbers >= 18.

In this case the filter will take in the search function as it’s argument.  For those who have never really done this before, just remember that if you want to pass a function within a function, simply reference it by name without the parentheses. We want to search for an instance of the same number within the two arrays.

And then we can wrap it all up like so:


  function diff(arr1, arr2) { 
    var newArr = arr1.concat(arr2); 

    function search(num) { 
      if (arr1.indexOf(num) === -1 || arr2.indexOf(num) === -1) { 
        return num; 
      } 
    } 
    return newArr.filter(search); 
  }

 

A shorter ES6 way…

 


function diffArray(arr1, arr2) { 
  var newArr = arr1.concat(arr2); 

  return newArr.filter((num) => {
    return (arr1.indexOf(num) === -1 || arr2.indexOf(num) === -1) 
  }); 
}

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

Alternative method: use a for loop.

But couldn’t you just use a for loop to iterate over the array? Yes, of course you could. That would look something like this:


function diffArray(arr1, arr2) {
  var result = [];
  // loop thru arr1 
  for (var i = 0; i < arr1.length; i++) {
    // if an index of arr2 is never found, push thru arr1
    if (arr2.indexOf(arr1[i]) === -1) {
      result.push(arr1[i]);
    }
  }
  for (var j = 0; j < arr2.length; j++) {
    if (arr1.indexOf(arr2[j]) === -1) {
      result.push(arr2[j]);
    }
  }
  return result;
}

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

Simply loop through each array and compare the two. If you find an instance of a number not within the other array, push it through to a new array and you’re good to go 🙂

If you have any comments, questions or feedback please leave me a message in the comments box below!


The Web Developers Bootcamp.

A n00b friendly guide to becoming a pro!

Learning to code can be seriously hard work. While I am oh so grateful for the opportunity to learn through Free Code Camp, I still find that learning to code alone and without proper guidance extremely exhausting.

Which is why I’ve started to substitute my education with an incredible online resource called the Web Developers Bootcamp courtesy of Udemy. This course has helped me brush off the cobwebs, unlearn my self-taught bad habits and gain a solid understanding of the true fundamentals of web development. It has helped me see why it is important to understand these JavaScript problems and how they apply to the real world.

This bootcamp will teach you how built beautiful sites with Bootstrap, add in functionality with JavaScript and write back end code with Node.js all in a series of short, sharp, no BS video modules. I seriously could not recommend it any higher. Check it out and let me know what you think 🙂

The Web Developers Bootcamp
The Web Developer Bootcamp.
The only course you need to learn web development – HTML, CSS, JS, Node, and More!

Sign up to receive up-to-date web tips, tricks and code hacks!