Perform a Union on Two Sets

Perform a Union on Two Sets


My union function is not pass , it print error final.indexOf is not a function !!!

Your code so far

function Set() {
    // the var collection will hold the set
    var collection = [];
    // this method will check for the presence of an element and return true or false
    this.has = function(element) {
        return (collection.indexOf(element) !== -1);
    // this method will return all the values in the set
    this.values = function() {
        return collection;
    // this method will add an element to the set
    this.add = function(element) {
            return true;
        return false;
   // this method will remove an element from a set
    this.remove = function(element) {
           var index = collection.indexOf(element);
            return true;
        return false;
    // this method will return the size of the set
    this.size = function() {
        return collection.length;
    // change code below this line
    this.union = function(arr) {
        for(var i = 0; i < arr.length; i++) {
            if(!this.has(arr[i])) {
        return this.values();
    // change code above this line

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36.

Link to the challenge:


I’m not seeing it in your code but that means somewhere you have called .indexOf on a variable named final except final is not an array. Do you have a variable ‘final’?


That’a all my code ! I never use final variable . Could it be a bug of question ?


Duh - I missed some things.

You are returning this.values() . The test is expecting you to return a Set object, not an array. this.values() returns an array.

Also, your function is based on an array parameter. The value actually passed to your function is also a Set, not an array.


Hi there. Since you have probably solved this, can you help me?

 this.union = function(insertedSet) {
        for(let i = 0; i < insertedSet.values().length; i++) {
            if(!this.has(insertedSet.values()[i])) {
         return this.values()

There’s apparently something wrong with my code since the console logs and error of ‘final.indexOf is not a function’. Can you please help? :slight_smile: :slight_smile: :slight_smile:


Based on alhazen1 answer, you must create a new Set object which it has the values is union-ed values from 2 sets and return it instead than add the different values directly to the first Set.