What is a collection in js ?

In javascript, we call a collection an array of objects, for example:

var collection = [  
    { id: 1, content: 'foo' },
    { id: 2, content: 'bar' }
];

Union ?

What we want to do is having one collection using multiple collections without duplicate elements. But to do that, we need to determine, what property identify our elements in our collections.

Let's do it!

Undercore.js has an union function but unfortunatelly, it applies only on arrays:

_.union(*arrays):

Computes the union of the passed-in arrays: the list of unique items, in order, that are present in one or more of the arrays.

_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);  
=> [1, 2, 3, 101, 10]

What we want to do, is to build our own function using the same logic than this one. For that, let's see how it works. In the annotated sources of underscore.js (http://underscorejs.org/docs/underscore.html#section-61), we have this:

_.union = function() {  
  return _.uniq(flatten(arguments, true, true));
};

If we look on the documentation, we can see that the _.uniq function can take a function as iterator (http://underscorejs.org/#uniq):

_.uniq(array, [isSorted], [iteratee]):

Produces a duplicate-free version of the array, using === to test object equality. In particular only the first occurence of each value is kept. If you know in advance that the array is sorted, passing true for isSorted will run a much faster algorithm. If you want to compute unique items based on a transformation, pass an iteratee function.

Perfect! We just have to do the same than the _.union function, but passing an iterator:

// collectionUnion(*arrays, iteratee)
function collectionUnion() {  
    var args = Array.prototype.slice.call(arguments);
    var it = args.pop();

    return _.uniq(_.flatten(args, true), it);
}

Nice! Now we just have to use it!
Here a full example:

// collectionUnion(*arrays, iteratee)
function collectionUnion() {  
    var args = Array.prototype.slice.call(arguments);
    var it = args.pop();

    return _.uniq(_.flatten(args, true), it);
}

var a = [{id: 0}, {id: 1}, {id: 2}];  
var b = [{id: 2}, {id: 3}];  
var c = [{id: 0}, {id: 1}, {id: 2}];

var result = collectionUnion(a, b, c, function (item) {  
    return item.id;
});

console.log(result); // [ { id: 0 }, { id: 1 }, { id: 2 }, { id: 3 } ]  

That's it! Thank you for reading and feel free to comment and give any suggestions :)