Diff Two Arrays - Why compare 2 arrays twice?

Hi, I have been stuck on this for awhile and when I looked at the answer I could understand to a certain extent but I just can’t for the life of me understand why you need to compare the 2 arrays twice as listed in the official answer.

onlyInFirst(arr1, arr2);
onlyInFirst(arr2, arr1);

I thought you would only need to compare once to find the odd elements out? Thank you in advance.

Your code so far

function diffArray(arr1, arr2) {
  var newArr = [];
  function onlyInFirst(first, second) {
  // Looping through an array to find elements that don't exist in another array
    for (var i=0;i<first.length;i++) {
      if (second.indexOf(first[i]) === -1) {
        // Pushing the elements unique to first to newArr
  onlyInFirst(arr1, arr2);
  onlyInFirst(arr2, arr1);
  return newArr;

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

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.91 Safari/537.36.

Link to the challenge:

Let’s use the following input from the challenge [1, "calf", 3, "piglet"], [1, "calf", 3, 4].

As the function name onlyInFirst() suggests, this will return all the elements that are present in the first array passed but not the second. By running onlyInFirst(arr1, arr2) we grab unique values from the first array (just "piglet" in this case) but what about the unique values in the second array (like 4)? We need to get them by calling onlyInFirst(arr2, arr1).

1 Like