Comparing Differences in Two Arrays
At our meetup Saturday, Kiley Dowling pair programmed with me and it was… different. But I’ve heard having someone peek over your shoulder whilst solving an algorithm is both helpful and a real world example of coding in the wild. The particular challenge of the day was to create function comparing two arrays with different values, and returning a new array containing unique; one with values unique to each array
My working solution was close, but not quite returning the right answer. Here is the function:
The solution I created before meeting today used the filter()
and indexOf()
functions. While on some level filtering the function, the results were not quite what I was hoping for:
This was returning an array minus duplicates. Why? Because by concating the two arrays first, there is no comparison done. I knew it was likely an important step to concat the arrays for better comparison, but my naivity on how indexOf()
actually works would explain my error. indexOf()
is a method of the Array object that returns the index of the first occurence of the specified value, or -1 if not found. The Array being traversed is not augmented, rather a new array is created with elements that returns a true value. The callback function takes three arguments:
So a better solution would be to filter the arrays seperately and concat their return values: