Diff Two Arrays
For today’s algorithm in the intermediate algorithm scripting series, we will be dealing with arrays again. For this algorithm, you will be given two arrays and output the difference between the two arrays. In other words, return an array containing number that are in either the first array or the second array but not both arrays. Let’s return to the wonderful chickeneggs representing the function inputs:
In order to find out of each number appears in both arrays, we will have to concatenate the two arrays and create one large array. Therefore when it comes time to look at each value in the large array, you can see if each value is in arr1 OR arr2 OR both. Let’s look at our concatenated array that we used using the concat() method.
Next up, we will run the fat chickenegg (above) that is our concatenated array through a filter method. What this method will do is create “a new array with all elements that pass the test implemented by the provided function.” What you do is pass a callback function (anonymous or not) and the function will have a test that determines whether or not it will be added the array. If it passes, then it will go, if not it will not go into the array.
Let’s imagine the filter method as a human character:
As the concatenated array goes through the filter array, this filter person opens his mouth which looks nothing more than black hole. This stretches the chickenegg before going into his mouth. Let’s go inside Mr.Filter’s mouth and see what is going on:
Starting with the first item in the array, Mr. Filter sees a 1 and uses combination of boolean, comparison operators and the indexOf() method to see if 1 exists either arr1 or arr2 (the two array inputs for the function)but not both. Since number 1, exists in both arrays, it does not pass. Next value:
Same thing, until we hit the next value:
As you can see, the number 4 exist in the array on the right but not on the left. That means that this value passes through filter and gets added to the array, the filter method will return when done. Let’s look at that array so far:
The value number 5 doesn’t pass through as it is found in both arrays. Even though the filter method will keep going but at the end:
1,2,3 and 5 are found in both arrays. What that means is the filter method returns an array that happens to only include 4 as it is only difference between the two arrays: