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]

N. Levenets
  • 77
  • 1
  • 1
  • 8
  • 1
    Where is your data and what you have tried so far? – Mohammad Usman Oct 16 '18 at 18:29
  • Sample data set please. – Mark Carpenter Jr Oct 16 '18 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. – trincot Oct 16 '18 at 18:36

1 Answers1

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]
Eugene Tsakh
  • 2,777
  • 2
  • 14
  • 27