5

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

Community
  • 1
  • 1
oneiros
  • 3,527
  • 12
  • 44
  • 71
  • Have you made any attempts to solve this already? If you have, what went wrong, what would you like us to help with? A part of the problem, or the whole of the problem? – David Thomas Jul 28 '12 at 20:45

3 Answers3

22
function diff(A, B) {
    return A.filter(function (a) {
        return B.indexOf(a) == -1;
    });
}
Casey Chu
  • 25,069
  • 10
  • 40
  • 59
6

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);
adeneo
  • 312,895
  • 29
  • 395
  • 388
3

Here:

var minus = function ( a, b ) {
    return a.filter(function ( name ) {
        return b.indexOf( name ) === -1;
    });
};

Live demo: http://jsfiddle.net/SjF9p/

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385