-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){.....}.

8
  • You would just return the array instance in your union function. Commented Jun 12, 2014 at 0:26
  • @incutonez Thanks! But I am very new to JS, could you give me some code example? Commented Jun 12, 2014 at 0:27
  • "Put code here" questions are too broad for Stack Overflow. You need to try something first. Commented Jun 12, 2014 at 0:28
  • What is the union function supposed to do? Commented Jun 12, 2014 at 0:28
  • There's already such a function, it's called concat() Commented Jun 12, 2014 at 0:28

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@Kuan OK. I've added some code to do an union.
-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/

3 Comments

This is exactly what concat() does btw ?
I know. The asker could just want an example of how to use Array.prototype. The question really needs clarification.
@Lindsay I agree. I've marked the question as a duplicate of stackoverflow.com/q/3629817/3210837.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.