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 :)
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With