0

I'm just asking how to make a function that will return the union of sets !!but without any libraries and package functions. Maybe, only cycles and basic array methods. Thanks in advance for any useful reply))

For instance: I have an array a = [1, 2, 3, 4] and b = [3, 4, 5, 6].

How do I get c = [1, 2, 3, 4, 5, 6]

3
  • 1
    Where is your data and what you have tried so far? Commented Oct 16, 2018 at 18:29
  • Sample data set please. Commented Oct 16, 2018 at 18:30
  • 1
    @N.Levenets, Given your comment at the first answer, please update your question so that you differentiate between your use of the word "set" and ES6 sets. And please show your effort. There is little appreciation for questions which show no research effort (hence the downvotes). Anyway, this question has been asked before, so better not waste more time on it. Commented Oct 16, 2018 at 18:36

1 Answer 1

3

If you mean ES6 sets then you can do it simply:

function union(...sets) { return new Set([].concat(...sets.map(set => [...set]))); } 

Then union(new Set([1, 2, 3]), new Set([3, 4, 5])); will return Set(4) {1, 2, 3, 4, 5}

If you need it to be done with ES5:

function unique(arr) { var result = []; for (var i = 0; i < arr.length; i++) { if (result.indexOf(arr[i]) === -1) { result.push(arr[i]); } } return result; } function union() { var result = []; for (var i = 0; i < arguments.length; i++) { result = result.concat(arguments[i]); } return unique(result); } 

And usage will be

union([1, 2, 3], [3, 4, 5], [4, 5, 6]); // => [1, 2, 3, 4, 5, 6] 
Sign up to request clarification or add additional context in comments.

3 Comments

Well, this is pretty good and reasonable, however I need it to be done without Set objects. Only arrays, strings and simple methods...
@N.Levenets added ES5 implementation
@Eugene_Tsakh That's pretty much what I wanted. Thanks a lot!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.