Skip to main content

Compare two arrays

Tutorial on comparing two arrays

Let's talk about comparing two array against each other and returning values that they have in common or values that they don't.

A bit of back story -- writing a function that will return common values was pretty easy for me to come up with however, returning unique values gave me some trouble and I spent quite a lot of time researching it. Eventually I found this neat solution and honestly I am not completely sure if I would get to it myself since I haven't been working enough with objects or this type of statement. Therefore, I will be going back to basics and I am planning to go through the Statements section on MDN.

The solutions 

By using For In... statement we can solve both problems and I am still trying to figure out if it's possible to apply For Loop in the unique values function.

Return common values

I used here a For Loop on both vowels and str arrays (string becomes an array when for loop is used on it) and compare every instance of each. Then we .push into a new empty array instances that match.

Return unique values

Here we are using a For In... statement that iterates properties of the str (string becomes an object in this case) and if the values of the array vowels are not included in the str we .push the unmatched values into an empty array.


Comments