0

Problem: Compare two arrays and return a new array with any items not found in both of the original arrays. Use Array.filter and Array.indexOf to solve this.

function diff(arr1, arr2) {
  var newArr = [];
  //code here
  return newArr;
}

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

I am not sure how to proceed. My solution is different from the above and uses a hard coded array. How do I make mine generic ?

function arrayNotContains(element){
    var arr = [1, 2, 3, 5];
    if(arr.indexOf(element) === -1){
        return true;
    }else{
        return false;
    }   
}

var filtered = [1, 2, 3, 4, 5].filter(arrayNotContains);
console.log(filtered);

I got one more solution below. Is that ok ?

var arr1 = [1,2,3,5];
var arr2 = [1,2,3,4,5];

var filtered = arr2.filter(function(num) {
    if (arr1.indexOf(num) === -1) return num;
});
stack1
  • 1,004
  • 2
  • 13
  • 28

1 Answers1

4

You will want to use a closure:

function notContainedIn(arr) {
    return function arrNotContains(element) {
        return arr.indexOf(element) === -1;
    };
}

var filtered = [1, 2, 3, 4, 5].filter(notContainedIn([1, 2, 3, 5]));
console.log(filtered); // [4]

Notice this is just a generalised version of your solution, I'm not saying that this is actually a valid solution for a symmetric diff function. For that, as it was stated in your problem, you'd need to do something like

function symmDiff(a, b) {
    return a.filter(notContainedIn(b)).concat(b.filter(notContainedIn(a)));
}
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Thanks. Please tell me if the second solution in my question is also ok or not. – stack1 Aug 06 '15 at 20:02
  • 1
    @stack1 - Doesn't the spec in your question require you get the non-overlapping values from *both* arrays? – Jared Farrish Aug 06 '15 at 20:04
  • @stack1: Apart from the wrong `return num` (which tymeJV wanted to correct in his now deleted answer?!), the approach with such an inline function expression is totally fine as well. Mine is basically just an abstraction of that, making it more suited for cases where you don't want/need those explicit `arr1`/`arr2` in your scope. – Bergi Aug 06 '15 at 20:15
  • 2
    [Hmm.](http://jsfiddle.net/jxgLj1Lz/1/) And [Hmm v2](http://jsfiddle.net/jxgLj1Lz/2/). – Jared Farrish Aug 06 '15 at 20:48
  • @stack1: Please see the disclaimer in my answer and JaredFarrish's comments. If you understand the difference between [difference](https://en.wikipedia.org/wiki/Complement_(set_theory)#Relative_complement) and [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) you surely will be able to figure out how to pass the test cases. – Bergi Aug 06 '15 at 20:53