5

This is a rather fundamental question but im looking for an optimal solution.I have 2 javascript String arrays. Lets 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 (with ordering preserved)

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

I dont really care for the second array B. Is there something in core javascript or jQuery that would help me? PS: Don't post nested for loops with IF statements. Possibly something smarter :)

karan
  • 77
  • 4
  • 1
    I don't have answer to this directly, but if you could convert the Array into an Object, you may be able to use this: if (B['Stark']) delete(A['Stark']); – Zathrus Writer Sep 06 '12 at 12:32

4 Answers4

5

A full jquery solution:

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);​
KyorCode
  • 1,477
  • 1
  • 22
  • 32
4

I suggest you to use the underscore.js lib, and specially the difference function. http://underscorejs.org/#difference

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

There are other useful tools in this lib.

odupont
  • 1,946
  • 13
  • 16
  • Ive already got a couple of jQuery libraries in my project. Wouldnt really want to add any more right now. Thanks though! – karan Sep 06 '12 at 13:08
1

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"]
Community
  • 1
  • 1
0

Maybe you want like

$(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);
});
Snake Eyes
  • 16,287
  • 34
  • 113
  • 221