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 :)

1
  • 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']); Sep 6, 2012 at 12:32

4 Answers 4

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);​
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.

1
  • Ive already got a couple of jQuery libraries in my project. Wouldnt really want to add any more right now. Thanks though!
    – karan
    Sep 6, 2012 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"]
1
  • Thank you. I shouldve looked harder.
    – karan
    Sep 6, 2012 at 13:07
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);
});
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.