0

So I let's say I have an array like this:

["one", "two", "three"]

And then I have another array like this:

["one", "two", "three", "four"]

I need my function to compare the two arrays and return "four". For example, I want the function to do nothing when the array does this:

["one", "two"]

But again, I want the function to return the difference when the array goes back to this:

["one", "two", "three"]

I've been playing with array.filter but so far, filter() has done everything but what I need it to. I know I could accomplish this with a complicated forEach() but I'd really like to avoid that.

Egee
  • 67
  • 2
  • 7
  • Do you want (1) all the elements in the second array that are not in the first, (2) all the elements in the first array that are not in the second, or (3) all the elements that appear in one array but not the other? – Ray Toal Nov 15 '18 at 07:39
  • I want the function to compare & return the (additions) difference between two arrays. – Egee Nov 15 '18 at 07:41
  • [The following answer](https://stackoverflow.com/a/52430020/1641941) is good. – HMR Nov 15 '18 at 08:03

2 Answers2

3

According to the first half of your question--

var a=["one", "two", "three"];
var b=["one", "two", "three", "four"]
var diff=b.filter((word) => !a.includes(word));
console.log(diff);
Monica Acha
  • 1,076
  • 9
  • 16
1

Modify the Array prototype:

Array.prototype.diff = function(a) {
    return this.filter(function(i) {return a.indexOf(i) < 0;});
};

Array.prototype.diff = function(a) {
    return this.filter(function(i) {return a.indexOf(i) < 0;});
};

console.log(["test1", "test2","test3","test4","test5","test6"].diff(["test1","test2","test3","test4"]));
Barr J
  • 10,636
  • 1
  • 28
  • 46
  • Please do not use this answer. Extending the prototype chain of built-in objects is a bad practice and should be done in rare circumstances. – KarelG Nov 15 '18 at 08:00