Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Strings from one Array if present in another

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

like image 680
karan Avatar asked Sep 06 '12 12:09

karan


2 Answers

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);​
like image 179
KyorCode Avatar answered Sep 23 '22 00:09

KyorCode


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.

like image 21
odupont Avatar answered Sep 23 '22 00:09

odupont