Perform Union on Two Sets,need help

Perform Union on Two Sets,need help
0

#1

Tell us what’s happening:
I am getting this error:Cannot read property ‘values’ of undefined.Need help

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) {
        if(!this.has(element)){
            collection.push(element);
            return true;
        }
        return false;
    };
   // this method will remove an element from a set
    this.remove = function(element) {
        if(this.has(element)){
           var index = collection.indexOf(element);
            collection.splice(index,1);
            return true;
        }
        return false;
    };
    // this method will return the size of the set
    this.size = function() {
        return this.length;
    };
    // change code below this line
    this.union=function(arr2){
        for(let i=0;i<arr2.length;i++){
            if(!collection.has(arr2[i])){
                collection.add(arr2[i]);
            }
            return this.values();
    }
    // change code above this line
}
}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/coding-interview-prep/data-structures/perform-a-union-on-two-sets


#2

I’m not 100% sure of that specific error message but I see a few things with your method that might be problems.

You are looping over arr2. Is arr2 really an array?
collection is an array. Does array have a method .has() ?
What data type are you returning? Or, is returning the result of this.values() what is expected?


#3

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])) {
                this.add(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 me? :slight_smile: