PDA

View Full Version : Consolidate two arrays


sudowork
08-14-2009, 04:11 PM
I'm creating an AJAX application where multiple users will be interacting with a single interface. I'm looking for a function of consolidating two different arrays, with common elements, into a single array.

For example:

var array1 = ['apple','orange','grape'];
var array2 = ['apple','grape','pear'];
var array3 = magicFunction(array1,array2);
//array3's contents = ['apple','orange','grape','pear']


Does this sound doable in a fairly fast manner, or am I going about this completely wrong?

I was thinking about just looping through both arrays and adding them to a third array, and during the second loop, if the element exists, don't add it.

jkd
08-14-2009, 06:34 PM
The issue is on how you store the data in the array. If you store it sorted, then you can determine the presence of an element in log(n) time. Javascript objects already have the overhead of using a hash lookup for object properties (which is amortized O(1) lookup), however, so you can simply take advantage of that. The below code sort of wraps the default dictionary behavior of Javascript objects into a Set object:

function Set() { this.elements = {} };

Set.prototype.add = function(el) {
this.elements[el.toString()] = el;
}

Set.prototype.remove = function(el) {
if (el.toString() in this.elements)
delete this.elements[el.toString()];
}

Set.prototype.contains = function(el) {
return el.toString() in this.elements;
}


Set.prototype.forEach = function(f) {
for (var el in this.elements)
f(this.elements[el]);
}

Set.prototype.map = function(f) {
var arr = [];
this.forEach(function(el) { arr.push(f(el)) });
return arr;
}

Set.prototype.filter = function(f) {
var arr = [];
this.forEach(function(el) { if (f(el)) arr.push(el) });
return arr;
}

// etc

jkd
08-14-2009, 09:29 PM
I guess I should actually answer your question too. Using the set class:


var set = new Set();
array1.forEach(function(el) { set.add(el) });
array2.forEach(function(el) { set.add(el) });


Then set will contain all the unique elements.