Diff Two Arrays filter question

Hey guys,

So I finally gave up and have solved the problem using two for loops, but for god-knows-how-long I have been trying to utilise filter() to create a new array from the elements that don’t match another.

My thinking process was that if I concat the arrays together, then sort them so that all matching elements are side-by-side, I could use filter to compare them. I tried to use

filter((a, b) => (a !== b));

to compare each element to the other, and it seemed to work as I got the first two matching elements (1 and 2) through, but not the other two matches. Strangely, it didn’t stop at the first element that didn’t match, it just stopped randomly (which makes me think that there was no way for it to work).

If anyone could shed some light on why I got half an array through but not the rest, I’d be very grateful :slight_smile:


/* My primitive, clunky for-loop solution

function diffArray(arr1, arr2) {
  var newArr = [];
  for (let j = 0; j < arr2.length; j++) {
    if (arr1.indexOf(arr2[j]) < 0) {
      newArr.push(arr2[j]);
    }
    if (arr2.indexOf(arr1[j]) < 0) {
      newArr.push(arr1[j]);
    }
  }
  return newArr;
}*/



// The method I wrote and am confused about:

function diffArray(arr1, arr2) {
  return arr1.concat(arr2).sort().filter((a, b) => a === b); // I would actually use "a !== b" here
}



/* A working solution of the method I was trying to figure out

function diffArray(arr1, arr2) {
  return arr1.concat(arr2).filter((item) => !arr1.includes(item) || !arr2.includes(item));
}*/



console.log(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]));
console.log(diffArray(["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]));

Your browser information:

User Agent is: Mozilla/5.0 (X11; CrOS x86_64 10718.88.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.118 Safari/537.36.

Link to the challenge:

the function passed to filter method will only accept one value of concated array, index and concated array itself. here b is index so no means to compare it.
you can do this to solve it with filter.

`let newarr1 = arr1.filter((a,i,arr) => arr2.some((b) => a===b);`
let newarr2 = arr2.filter((a,i,arr) => arr1.some((b) => a===b);`
newArr = newarr1.concat(newarr2);