The _array and _hash refer to the same objects, and therefore the memory overhead is limited to references in the array and hash, but not full copies of the objects.
Violin: http://jsfiddle.net/vbjWK/
function UniqueArray(array, key) { this._array = []; this._hash = {}; this._key = key; this.concat(array); } UniqueArray.prototype.concat = function(array) { var i, len; for (i = 0, len = array.length; i < len; i++) { this.push(array[i]); } } UniqueArray.prototype.push = function(obj) { if (!this._hash[obj[this._key]]) { this._hash[obj[this._key]] = obj; this._array.push(obj); } }
Test:
// Testing testing var first = [ {"value": "1", "id": "123"}, {"value": "2", "id": "124"}, {"value": "3", "id": "125"} ]; var second = [ {"value": "1", "id": "123"}, {"value": "2", "id": "234"}, {"value": "3", "id": "235"} ] var ua = new UniqueArray(first, "id"); ua.concat(second); console.log(ua._array);
source share