-2

Right now, what I want to do is write an Array.prototype function union( array_to_union ), and I want to call it like this below:

var a = [1,2,3];
a.union([2,3,4]).union([1,3,4]) ......

and the result will be the union of those array, I wonder how can I do that?

I only know I should use Array.prototype.union = function( array_to_union){.....}.

Toothbrush
  • 2,080
  • 24
  • 33
Kuan
  • 11,149
  • 23
  • 93
  • 201

2 Answers2

2

How about this:

Array.prototype.union = function (second) {
    return second.reduce(function (array, currentValue) {
        if (this.indexOf(currentValue) === -1) array.push(currentValue);

        return array;
    }, this).sort();
};

Test

var a = [1,2,3];
a = a.union([2,3,4]).union([1,3,4]);

Result

a = [1, 2, 3, 4]

It also sorts the array, as your examples showed in the comments.

Toothbrush
  • 2,080
  • 24
  • 33
-1

Union function that can be chained together:

Array.prototype.union = function(array_to_union) {
    for (i = 0; i < array_to_union.length; i++) {
        this.push(array_to_union[i]);
    }
    return this;
}


var a = [1,2,3];              
a.union([4,5,6]).union([7,8,9]);

Note: in this case, the union function just adds 1 array onto the other (does not care about sorting or distinct values).

JS fiddle with more examples: http://jsfiddle.net/enW2Y/1/

Lifes
  • 1,226
  • 2
  • 25
  • 45