Wednesday, October 10, 2012

subtract one array from another in JavaScript

In this example, Bar contains a subset of the items in Foo. Baz will end up with all of the items in Foo not in Bar. The lines in black are helpful, not required.

function DefineBaz() {
   
var DiagnosticsHelper = "";
   Variables.Baz = new Array();
   for (var x = 0; x < Variables.Foo.length; x++) {
      var isMatch = false;
      for (var y = 0; y < Variables.Bar.length; y++) {
         if (Variables.Foo[x].UserID == Variables.Bar[y].UserID) {
            isMatch = true;
         }
      }
      if (!isMatch) {
         Variables.Baz.push(Variables.Foo[x]);
      }
   }
   
for (var z = 0; z < Variables.Baz.length; z++) {
      DiagnosticsHelper = DiagnosticsHelper + Variables.Baz[z].UserID + " ";
   }
   document.getElementById("whatever").innerHTML = DiagnosticsHelper;

}

 
 

You can probably see how the DiagnosticsHelper could be moved about in code to collect values from Foo and Bar also.

No comments:

Post a Comment