0

I have two arrays of strings in vmware orchestrator, a and b.

I want to push all strings from a EXCEPT those that are also found in b into a new third array, c. So b is an array that contains exclusions.

I found some code from this site which I tried but it did not work as intended.

var c = new Array();

if (b.length == 0) {
    var c = a
} else

    for (i = 0; i < a.length; i++) {
    for (j = 0; j < b.length; j++) {
        if (b[j] != a[i]) {

            c.push(a[i]);
        }
    }
}

So in the above example. if b contains nothing then it goes ahead and make c indentical to a.

a contains three values, Test, Test2 and Test3.

If b contains Test it will add all but this into c. (c = Test2 and Test3)

Now to the problem. If b contains Test and Test2, it will NOT exclude both, instead c will contain Test, Test 2, Test3 and Test3. I want it to contain just Test3 at this stage.

Andrea Casaccia
  • 4,802
  • 4
  • 29
  • 54
Fredrik
  • 27
  • 1
  • 1
  • 5

1 Answers1

0

First of all this is javascript. Now see the below for solution. Dont push the elements blindly. Instead navigate through the entire array to make sure that there are no matches.

var a = ["Test","Test2","Test3"];
var b = ["Test","Test2"];
var c = new Array();

if (b.length == 0) {
var c = a;
} else {

for (var i = 0; i < a.length; i++) {
    var count = 0;
    for (var j = 0; j < b.length; j++) {
        if (b[j] == a[i]) {
            count++; 
        }
    }
    if(count == 0) {
        c.push(a[i]);
    }
}
}
alert(c);
Dinal
  • 661
  • 4
  • 9
  • Thanks, but sadly it doesnt fully work. With two values in b it adds all from a to c, altho with the above it does not add a duplicate of the last value in a to c. With only one value in b or none, it works as wanted. – Fredrik Jun 12 '14 at 11:00
  • @Fredrik, I have edited the answer. This works perfectly. I posted the previous without testing. My bad.. – Dinal Jun 12 '14 at 11:09