Javascript - Compare two arrays, return differences, BUT

I found a lot of posts that solve this problem:

Assuming we have:

array1 = ['A', 'B', 'C', 'D', 'E']; array2 = ['C', 'E']; 

Is there a proven and quick solution for comparing two arrays with each other, returning one array without the values ​​displayed in both arrays (here and here C and E). Desired solution:

 array3 = ['A', 'B', 'D'] 

But what if you have:

 array1 = ['A', 'B', 'C', 'D', 'D', 'E']; array2 = ['D', 'E']; 

and you are looking for a solution:

 array3 = ['A', 'B', 'C', 'D'] // don't wipe out both D's 

Here is the context:

You are trying to teach students how sentences work. You give them an encrypted sentence:

ate - cat - mouse - the -

They begin to type the answer: Cat

You want the prompt to appear:

ate - mouse -

Currently my code is returning both.

Here is what I tried:
(zsentence is a copy of xsentence that will be processed by the code below, join () ed and placed on the screen)

 for (i=0; i < answer_split.length; i++) { for (j=0; j < xsentence.length; j++) { (function(){ if (answer_split[i] == xsentence[j]) { zsentence.splice(j,1); return; } })(); } } 
+4
source share
2 answers

Just iterate over the array of elements you want to remove.

 var array1 = ['A', 'B', 'C', 'D', 'D', 'E']; var array2 = ['D', 'E']; var index; for (var i=0; i<array2.length; i++) { index = array1.indexOf(array2[i]); if (index > -1) { array1.splice(index, 1); } } 

It O(array1.length * array2.length) , but for reasonably small arrays and for modern equipment this should not remotely cause a problem.

http://jsfiddle.net/mattball/puz7q/

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/splice

+12
source

You can also use Filter. Please see the example below.

 var item = [2,3,4,5]; var oldItems = [2,3,6,8,9]; oldItems = oldItems.filter(function(n){ return item.indexOf(n)>-1?false:n;}); 

so it will return [6,8,9]

and if you want to get only consistent elements, then you should write the code below.

 oldItems = oldItems.filter(function(n){ return item.indexOf(n)>-1?n:false;}); 

This will return only [2,3].

0
source

All Articles