Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function that returns difference of two arrays of strings in javascript [duplicate]

Possible Duplicate:
What is the fastest or most elegant way to compute a set difference using Javascript arrays?

I need help with devising a function that will return the difference between two arrays of strings in Javascript (jQuery is acceptable as well).

I am basically looking for a function that calculates array A minus B.

So if we have the followin"

A = ['Istanbul', 'Hong Kong', 'Berlin'];
B = ['Berlin', 'Bonn'];

Calling diff = minus(A,B) should result with diff being populated with the following values ['Istanbul', 'Hong Kong']

I do not want to use an additional library like JS Set.

Please help with suggestions ...

like image 262
oneiros Avatar asked Jul 28 '12 20:07

oneiros


People also ask

How do you return the difference between two arrays?

To get the difference between two arrays: Use the filter() method to iterate over the first array. Check if each element is not contained in the second array. Repeat the steps, but this time iterate over the second array.

Which function finds out difference between two arrays?

The array_diff() function compares the values of two (or more) arrays, and returns the differences. This function compares the values of two (or more) arrays, and return an array that contains the entries from array1 that are not present in array2 or array3, etc.

How do I compare two arrays of arrays?

Using Arrays. equals(array1, array2) methods − This method iterates over each value of an array and compare using equals method. Using Arrays. deepEquals(array1, array2) methods − This method iterates over each value of an array and deep compare using any overridden equals method.


2 Answers

function diff(A, B) {
    return A.filter(function (a) {
        return B.indexOf(a) == -1;
    });
}
like image 93
Casey Chu Avatar answered Oct 06 '22 02:10

Casey Chu


The fastest would probably be a regular loop

var A = ['Istanbul', 'Hong Kong', 'Berlin'],
    B = ['Berlin', 'Bonn'],
    C = [];

for (var i=A.length; i--;) {
   if (B.indexOf(A[i]) === -1) 
       C.push(A[i]);
}

console.log(C);

The most elegant is opinion-based, but something like

var A = ['Istanbul', 'Hong Kong', 'Berlin'],
    B = ['Berlin', 'Bonn'];

var C = A.filter(x => !B.includes(x));

console.log(C);
like image 38
adeneo Avatar answered Oct 06 '22 01:10

adeneo