Remove rows from one array if they are present in another

This is a fairly fundamental question, but I'm looking for the best solution. I have 2 javascript String arrays . Let's say

A: ["Stark", "Targaryen", "Lannister", "Baratheon"]
B: ["Greyjoy", "Tyrell", "Stark"]

Since "Stark" is repeated, I want to remove it from array A, and my result should be (keeping order)

A: ["Targaryen", "Lannister", "Baratheon"]

I really don't care about the second array of B. Is there something mostly javascript or jQuery that would help me? PS: Do not send nested for loops with IF statements. Maybe something smarter :)

+5
source share
4 answers

Complete solution for jquery:

var a = ["Stark", "Targaryen", "Lannister", "Baratheon"];
var b = ["Greyjoy", "Tyrell", "Stark"];

var result = $.grep(a, function(n, i) {
    return $.inArray(n, b) < 0;
});

alert(result);​
+5
source

underscore.js lib . http://underscorejs.org/#difference

_.difference([1, 2, 3, 4, 5], [5, 2, 10]);
=> [1, 3, 4]

lib .

+4

From another answer

Array.prototype.diff = function(a) {
    return this.filter(function(i) {return !(a.indexOf(i) > -1);});
};

////////////////////  
// Examples  
////////////////////

[1,2,3,4,5,6].diff( [3,4,5] );  
// => [1, 2, 6]

["test1","test2","test3","test4","test5","test6"].diff(["test1","test2","test3","test4"]);      
// => ["test5", "test6"]
+1
source

You might like it

$(function(){
   var A = ["Stark", "Targaryen", "Lannister", "Baratheon"];
   var B = ["Greyjoy", "Tyrell", "Stark"];

    $.each(A, function (key, value) {
        if($.inArray(value, B) > -1) {
            A.splice($.inArray(value, B), 1);
        }
    });

    document.write(A);
});
0
source

All Articles