Intermediate algorithm FreeCodeCamp: Diff Two Arrays

Intermediate algorithm FreeCodeCamp: Diff Two Arrays

·

3 min read

The challenge from FreeCodeCamp:

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.

Note: You can return the array with its elements in any order.

Explanation: Basically we need to compare two arrays arr1 and arr2, and create an algorithm/program that identifies any number not present in both arrays.

As always in programming there many ways to solve the problem here is one divided into steps:

Step 1: Declare a function that takes two parameters(our arrays)

function diffArray(arr1,arr2);

Step 2: Declare a variable newArr = [] for the only purpose to create an empty array [] and be filled up later with the push() method;

var newArr = [];

Step 3: For both arrays, we use the forEach method which applies the "call back function" that we create.

arr1.forEach(callBackFunction)

Step4: We create the call back function to pass it as the forEach() method parameter. Very very important note, the callback function must always have at least one parameter, here is called item this parameter represents the items of the array linked with the dot notation to the forEach() method.

arr1.forEach(function (item)

here with the arrow function:

arr1.forEach(item=>

STEP 5:

As body of the callback function we place a conditional statement if so we basically tell to the callback function, if the arr2 (which is the second array) have value that are not in the arr1 let me know.

How does that?

We use the method indexOf() linked with the dot notation to the arr2 and as parameters, we pass item (which represent all the items of the arr1):

  if (arr2.indexOf(item)=== -1)

So the dynamic of the above algorithm is that forEach() will loop for all the element of arr1 and will apply the conditional statement for all elements of arr2.

The method indexOf() if cannot find an element in the array gives a default value of -1, so in case the two compared array have different values, indexOf() will tell us giving the default value of -1.

STEP 6:

Once the if statement is equal to -1, we can pass the parameter (of arr1) to the newArr using the push() method.

if (arr2.indexOf(item)=== -1){ newArr.push(item) }

STEP 7:

Since we are comparing so far arr1 versus arr2 the limitation is that we are going through elements of arr1 that are all included in arr2 (1235 are all included in 12345) so we are not satisfying the FreeCodeCamp challenge requirements.

To fix this we do the opposite comparing arr2 versus arr1 and we are done:

> function diffArray(arr1, arr2) {
  var newArr = [];
arr1.forEach(item=>{
  if (arr2.indexOf(item)=== -1){
    newArr.push(item)
  }

})

arr2.forEach(item=>{
  if (arr1.indexOf(item)=== -1){
    newArr.push(item)
  }

})

  return newArr;
}

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