What does my code work for the diff two arrays challenge

What does my code work for the diff two arrays challenge
0

#1
function diffArray(arr1, arr2) {
  var newArr = [];
  var arr = arr1.concat(arr2);
   for(var i = 0; i < arr.length; i++) {
  if(arr1.indexOf(arr[i]) === -1 ||arr2.indexOf(arr[i]) === -1) {
    newArr.push(arr[i]);
  }
}
  return newArr;
}

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

I was trying different possible solution and sort of stumbled this solution. Can someone explain to me why it works? Thanks.


#2

Once you have created a new array with the combined elements of both arrays, you iterated through this new array and if either of the original arrays (arr1 or arr2) has an element which is not in found in the new array, then you add the element to a final array (newArr) which is returned after the combined array has been fully iterated.


#3

Thanks. I was looking at it some more and was starting to understand it more, but your explanation clears up any other doubts.


#4

Another approach with the same basic logic is a little more readable in my opinion:

function diffArray(arr1, arr2) {
  var newArr = [];
  var arr = arr1.concat(arr2);
  for (var i = 0; i < arr.length; i++) {
    if(!arr1.includes(arr[i]) || !arr2.includes(arr[i])) {
      newArr.push(arr[i]);
    }
  }
  return newArr;
}

#5

Or if you prefer the filter function using the above includes function:

function diffArray(arr1, arr2) {
  return arr1.concat(arr2).filter(function(elem) {
    return !arr1.includes(elem) || !arr2.includes(elem); 
  });
}

#6

What is it supposed to do?

Edit: never mind. :blush:


#7

I get that ES6 can’t be used in the FCC editor, so I’m not being to be a smarty-pants, but the first time I wrote a solution to this problem, it took me ~20 lines [0] and I just realised it can be done in one now

function diffArray(a1, a2)[…a1, …a2].filter((e) => (!a1.includes(e) || !a2.includes(e)))

or like this

let diffArray = (a1, a2) => […a1, …a2].filter((e) => (!a1.includes(e) || !a2.includes(e)))

The first one works but doesn’t format correctly in my editor. ES6 is awesome.

[0] because I was bad, not javascript


#8

You technically do not need those parentheses around the e or the return block of the arrow function:

const diffArray = (a1, a2) => […a1, …a2].filter(e => !a1.includes(e) || !a2.includes(e));

And I agree ES6 syntax is great, but I did not want to assume the OP had experience with ES6.