spudly.shuoink.com

the best way to predict the future is to implement it

Entries Comments


Array.union();

31 May, 2008 (15:36) | JavaScript

Here’s another set theory prototype for the Array object in JavaScript. This one performs a union of the two arrays.

Usage;

var setA = [ 1, 2, 3, 4, 5, 6 ];
var setB = [ 4, 5, 6, 7, 8 ];
var union = setA.union( setB ); // Now union is [ 1, 2, 3, 4, 5, 6, 7, 8 ];
Array.prototype.union = function( setB ) {
   var setA = this;

   var seen = {};
   var union = [];

   for ( var i = 0; i < setA.length; i++ ) {
      if ( !seen[ setA[i] ] ) {
         union.push( setA[i] );
         seen[ setA[i] ] = true;
      }
   }
   for ( var i = 0; i < setB.length; i++ ) {
      if ( !seen[ setB[i] ] ) {
         union.push( setB[i] );
         seen[ setB[i] ] = true;
      }
   }

   return union;
};

« Array.intersection()

 Array.complement(); »

Write a comment