spudly.shuoink.com

the best way to predict the future is to implement it

Entries Comments


Array.difference();

31 May, 2008 (17:00) | JavaScript

Here’s a prototyped method for Array that computes the symmetric difference between two arrays. It basically returns all the values that are in one or the other array but not both.

Usage:

var setA = [ 1, 2, 3, 4, 5, 6 ];
var setB = [ 4, 5, 6, 7, 8, 9, 10 ];
var diff = setA.difference( setB ); // diff is now [ 1, 2, 3, 7, 8, 9, 10 ]
Array.prototype.difference = function( setB ) {
   var setA = this;

   var setA_seen = {};
   var setB_seen = {};

   for ( var i = 0; i < setB.length; i++ ) {
      setB_seen[ setB[i] ] = true;
   }
   for ( var i = 0; i < setA.length; i++ ) {
      setA_seen[ setA[i] ] = true;
   }

   var difference = [];
   for ( var i = 0; i < setA.length; i++ ) {
      if ( !setB_seen[ setA[i] ] ) {
         difference.push( setA[i] );
      }
   }
   for ( var i = 0; i < setB.length; i++ ) {
      if ( !setA_seen[ setB[i] ] ) {
         difference.push( setB[i] );
      }
   }
   return difference;
};

« Array.complement();

 Array.min() && Array.max() && Array.sum() »

Comments

Comment from mark evans
Time: June 2, 2008, 8:06 pm

i could be wrong, but i think you only need one loop to iterate over both arrays simultaneously to create a hash which contains the xor of the two arrays, then another to extract the result.

Array.prototype.difference = function(aryB){
var len = Math.max(this.length, aryB.length),
i,p, result=[], tmp,
diff = {};
for(i=0;i<len;i++){
if(i<this.length)
diff[ this[i] ] = diff[this[i]] ? 2 : 1;
if(i<aryB.length)
diff[ aryB[i] ] = diff[aryB[i]] ? 2 : 1;
}
for(p in diff)
if( diff[p]==1 ) result.push(p);
return result;
}

Comment from spudly
Time: June 3, 2008, 6:21 am

Nice suggestion. I’m sure your method more efficient.

Write a comment