Brad Thomas
Brad Thomas

Reputation: 103

Javascript -- Compare two arrays, return differences, BUT

I've 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 fast solution to compare two arrays against each other, returning one array without the values appearing in both arrays (C and E here). Desired solution:

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

But what if you have:

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

and you're looking for the solution to be:

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

Here is some context:

You are trying to teach students about how sentences work. You give them a scrambled sentence:

ate -- cat -- mouse -- the -- the

They start typing an answer: The cat

You would like the prompt to now read:

ate -- mouse - the

At present, my code takes out both the's.

Here is what I've tried:
(zsentence is a copy of xsentence that will get manipulated by the code below, join()ed and put to 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; }
        })();
    }
}

Upvotes: 7

Views: 23791

Answers (2)

Ashish Bhanderi
Ashish Bhanderi

Reputation: 507

You can use Filter also. Please review below example.

var item = [2,3,4,5];
var oldItems = [2,3,6,8,9];
oldItems = oldItems.filter(n=>!item.includes(n))

so this will return [6,8,9]

and if you want to get only matched items then you have to write below code.

oldItems = oldItems.filter(n=>item.includes(n))

This will return [2,3] only.

Upvotes: 8

Matt Ball
Matt Ball

Reputation: 359776

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's O(array1.length * array2.length) but for reasonably small arrays and on modern hardware this shouldn't remotely cause an issue.

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

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

Upvotes: 16

Related Questions