Reply
Returning the non-intersection of two arrays
Old 08-20-2006, 01:01 PM Returning the non-intersection of two arrays
bez
bez's Avatar
Skilled Talker

Posts: 53
Ive got 2 arrays, array1 and array2, that store integer values. Id like a function that takes the two arrays and returns an array with every value that is in array1 and not array2 and array2 but not array1, so:

array1(1,2,3,4,5,6)
array2(3,4,5,6,7,8)

nonIntersect(array1, array2) = array(1,2,7,8)

The order of elements is not important.

Javascripts inbuilt array functions dont seem to helpful for this. The only way i can think to perform this would be to iterate over every value in array1 against everything from array2. There has to be a better way!

Cheers for any feedback.
bez is offline
Reply With Quote
View Public Profile
 
When You Register, These Ads Go Away!
Old 08-20-2006, 03:41 PM Re: Returning the non-intersection of two arrays
bez
bez's Avatar
Skilled Talker

Posts: 53
figured it out all on my own! if anyone can improve please let me know:

// Array.unique( strict ) - Remove duplicate values
Array.prototype.unique = function( b ) {
var a = [], i, l = this.length;
for( i=0; i<l; i++ ) {
if( a.indexOf( this[i], 0, b ) < 0 ) { a.push( this[i] ); }
}
return a;
};

//return non-intersection from self and another array
Array.prototype.nonIntersect = function nonIntersect(array2) {
//create a copy, dont work on original
array1 = this;
var differenceArray = new Array();
array1 = array1.unique();
array1.sort();
array2 = array2.unique();
array2.sort();

for (i=0; i<array1.length; i++) {
//if array2 is empty everything in array1 is unique, so add it to differenceArray and quit
if (array2.length == 0) {
differenceArray = array1.concat(differenceArray);
break;
}
if (array1[i] < array2[0]) {
differenceArray[differenceArray.length] = array1[i];
continue;
}
if (array1[i] == array2[0]) {
array2.shift();
continue;
}
if (array1[i] > array2[0]) {
differenceArray[differenceArray.length] = array2[0];
array2.shift();
//need to check array[i] again so remove the effect of incrementation here:
i--;
continue;
}
}
//if there are any elements remaining in array2 they must not be in array1 so add to differenceArray
if (array2.length > 0) {
differenceArray = array2.concat(differenceArray);
}
return (differenceArray.sort());
};
bez is offline
Reply With Quote
View Public Profile
 
Reply     « Reply to Returning the non-intersection of two arrays
 

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are Off




   
RSS Feed  Feeds: RSS   JS   XML
RSS Feed  Feeds for this forum: RSS   JS   XML

 


Page generated in 0.11134 seconds with 12 queries