This next challenge, Diff Two Arrays, will have us write a function that takes in two arrays, and should return a single array containing those values that are not present in any of these two input arrays.
To illustrate you with a few examples:
diff([1, 2, 3], [2, 3, 4]); //-> [1, 4] diff([1, 2, 3], [10, 11, 12]); //-> [1, 2, 3, 10, 11, 12] diff([1, 2, 3], [1, 2, 3]); //-> []
We have quite a few ways to go about this exercise. Using two (2) for loops and using indexOf and push seems to be the easiest way, but the easiest way may not be the best. This time, we’ll use the filter method and a few others to get it done.
We are going to filter each array individually, and check for values that are present in the other array (using indexOf). To finish it off, we’ll concatenate these two filtered arrays and get a return value.
function diff(arr1, arr2) { return arr1.filter(function(item) { return arr2.indexOf(item) < 0 ? true : false; }).concat( arr2.filter(function(item) { return arr1.indexOf(item) < 0 ? true : false; }) ); }
Look at that! Doesn’t it look confusing? It’s actually quite simple,let’s do it step by step:
function diff(arr1, arr2) { var filtered1 = arr1.filter(function(item) { return arr2.indexOf(item) < 0 ? true : false; }); var filtered2 = arr2.filter(function(item) { return arr1.indexOf(item) < 0 ? true : false; }); return filtered1.concat(filtered2); }
We firts get a filtered version of both arrays. We filter by getting the indexOf property of the current item in the other array, if the returned value is below zero, it means that the item is not present in that other array and so, it should be returned. Once both arrays have been filtered, we use the concat method, which simply concatenates both arrays and returns a single array.
The previous version simply does all of the steps without the need of any extra variables, and returns the answer at once.
Give it a shot, make use of for loops and come up with an alternative answer if you can!