Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript -- Compare two arrays, return differences, BUT

Tags:

javascript

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; }
        })();
    }
}
like image 992
Brad Thomas Avatar asked Jan 25 '13 04:01

Brad Thomas


People also ask

Can you compare two arrays in JavaScript?

While JavaScript does not have an inbuilt method to directly compare two arrays, it does have inbuilt methods to compare two strings. Strings can also be compared using the equality operator. Therefore, we can convert the arrays to strings, using the Array join() method, and then check if the strings are equal.


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'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

like image 90
Matt Ball Avatar answered Oct 30 '22 10:10

Matt Ball


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.

like image 21
Ashish Bhanderi Avatar answered Oct 30 '22 11:10

Ashish Bhanderi