Diff Two Arrays

Learn how to solve the freeCodeCamp algorithm 'Diff Two Arrays' using the Array.indexOf() JavaScript method and a for-loop.

Diff Two Arrays

In this freeCodeCamp problem we will create an algorithm that compares two arrays and returns a new array made up of only the unique items that appear in only one of the given arrays.

For instance, if arr1 contains [1,2,3] and arr2 contains [2,3,4], then newArr would be [1,4].

Requirements

  • diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]) should return an array
  • ["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"] should return ["pink wool"]
  • ["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"] should return an array with one item
  • ["andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"] should return ["diorite", "pink wool"]
  • ["andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"] should return an array with two items
  • ["andesite", "grass", "dirt", "dead shrub"], ["andesite", "grass", "dirt", "dead shrub"] should return []
  • ["andesite", "grass", "dirt", "dead shrub"], ["andesite", "grass", "dirt", "dead shrub"] should return an empty array
  • [1, 2, 3, 5], [1, 2, 3, 4, 5] should return [4].
  • [1, 2, 3, 5], [1, 2, 3, 4, 5] should return an array with one item.
  • [1, "calf", 3, "piglet"], [1, "calf", 3, 4] should return ["piglet", 4]
  • [1, "calf", 3, "piglet"], [1, "calf", 3, 4] should return an array with two items.
  • [], ["snuffleupagus", "cookie monster", "elmo"] should return ["snuffleupagus", "cookie monster", "elmo"]
  • [], ["snuffleupagus", "cookie monster", "elmo"] should return an array with three items.
  • [1, "calf", 3, "piglet"], [7, "filly"] should return [1, "calf", 3, "piglet", 7, "filly"]
  • [1, "calf", 3, "piglet"], [7, "filly"] should return an array with six items.

Psuedocode

Let's see what we need to do in order to create one array of only unique items when we are given 2 separate arrays.

// Create a function that accepts 2 arrays as arguments
    
    // Create a new array to store the unique items
    
    // Loop through items in second array
        // Check if current item exists in first array
        // If no, add it to the new, unique array
        // Otherwise do nothing
        
    // Loop through the items in the first array
        // Check if the current item exists in the second array
        // If no, add it to the new, unique array
        // // Otherwise do nothing
        
    // Return the new array

Solving the Algorithm

Setting up the function

Let's start off with the boilerplate function given to us from freeCodeCamp that accepts two arrays - arr1 and arr2 as arguments, gives us a newArr to store the unique items, and returns newArr when it's all said and done.

function diffArray(arr1, arr2) {
  var newArr = [];
  // Same, same; but different.
  return newArr;
}

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

Looping through the arrays

Let's create the loops that will iterate over arr1 and arr2 that will check if the current item exists in the other array.

For this we will use the Array.indexOf() method.

Here's a snippet straight from the MDN docs:

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

I've highlighted the or -1 if it is not present because this will be a great way for us to check whether or not that item exists in the other array while we are iterating through it.

Quick Example of Arr.indexOf()

Here's a quick overview as to how we can use the .indexOf() method:

const cars = ['Audi', 'BMW', 'Mercedes', 'Ferrari'];

cars.indexOf('BMW') // Returns index 1

cars.indexOf('Lamborghini') // Returns -1 because it does not exist in 'cars' array

Since we're looking for unique items, anything that returns -1 while we're iterating through one array and checking the .indexOf() of the other will be something we want to Array.push() to newArr.

Our first loop will look something like this:

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

    // Loop through arr2
    for (var i in arr2) {
        // If current items does not exist in arr1
        if (arr1.indexOf(arr2[i]) === -1) {
            // Add it to newArr
            newArr.push(arr2[i])
        }
      }  	
  return newArr;
}
diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]); // Returns 4

Try this the code snippet in your browser console.

You'll notice that this seems to work as expected, it's looping through arr2 and giving us the item that's not in arr1, which in this case is 4.

In fact, about half of the requirements freeCodeCamp has will end up passing. The reason that the solution isn't complete is because it also needs to iterate through all of the items in arr1 and cross reference them with the items in arr2

For instance, passing in this argument [1, "calf", 3, "piglet"], [1, "calf", 3, 4] returns [4] when it should return ["piglet", 4].

The single loop iterates through arr2 and checks if arr1 contains 1 - yep, "calf" - yep, 3 - yep, 4 - nope. So it then pushes 4 to newArr and calls it a day. We also need to do the same thing for the other array. So with that said, let's add another loop for this.

The Solution

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

    for (var i in arr2) {
        if (arr1.indexOf(arr2[i]) === -1) {
            newArr.push(arr2[i])
        }
      }
      for (var i in arr1) {
          if (arr2.indexOf(arr1[i]) === -1) {
              newArr.push(arr1[i])
          }
      }
    	
  return newArr;
}
// diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
// diffArray(["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]);
// diffArray(["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]);
// diffArray(["andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]);
// diffArray(["andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]);
// diffArray(["andesite", "grass", "dirt", "dead shrub"], ["andesite", "grass", "dirt", "dead shrub"]);
// diffArray(["andesite", "grass", "dirt", "dead shrub"], ["andesite", "grass", "dirt", "dead shrub"]);
// diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
// diffArray([1, "calf", 3, "piglet"], [1, "calf", 3, 4]);
// diffArray([], ["snuffleupagus", "cookie monster", "elmo"]);
diffArray([1, "calf", 3, "piglet"], [7, "filly"]);

Try this the code snippet in your browser console.

Great Job 💻

Thanks for sticking with me on this freeCodeCamp intermediate algorithm walkthrough for "Diff Two Arrays". I'd love to hear any questions or feedback and if you have a solution that's a little more straight-to-the-point please let me know!

Shoot me an email at [email protected] with any questions and if you enjoyed this, stay tuned and subscribe below! 👇

Help us improve our content