Home > Enterprise >  JavaScript Object of Array
JavaScript Object of Array

Time:04-06

I'm following the freeCodeCamp tutorial (https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/create-a-set-class) to create a set. I'm confused by the dictionary property & building the class (not instantiating it but thank you for the replies). Is it an array? Is it an object without key value pairs? The example they gave makes it seem that way for my second question:

const set1 = new Set([1, 2, 3, 5, 5, 2, 0]);
console.log(set1); // output: {1, 2, 3, 5, 0}

When I treat it like an array, it doesn't work. So how do I create an add or remove method to class Set?

class Set {
    constructor() {
        // Dictionary will hold the items of our set
        this.dictionary = {};
        this.length = 0;
    }
    add(element){

        dictionary.push(element) // fails
    }
    remove(element){
        if(dictionary.indexOf(element) === -1) // fails

    }
}

CodePudding user response:

dictionary should be this.dictionary.

{} creates an object. Objects don't have push() or indexOf() methods. To add a new element to an object, assign to a property name. There's no need to test if the element is in the object when removing, just use delete to remove the element; if the key doesn't exist, it won't do anything.

You can use an object to represent a set by using the object keys as the set elements, since keys can't be duplicated. The value can be anything, it's ignored, because we're only using the keys.

If you do want to test whether a key exists, you can use if (this.dictionary.hasOwnProperty(element))

class MySet {
  constructor() {
    // Dictionary will hold the items of our set
    this.dictionary = {};
  }
  add(element) {
    this.dictionary[element] = null;
  }
  remove(element) {
    delete this.dictionary[element];
  }
  get length() {
    return Object.keys(this.dictionary).length;
  }
}

let s = new MySet();
s.add("foo");
s.add("bar");
console.log(Object.keys(s.dictionary));
s.remove("foo");
console.log(Object.keys(s.dictionary));

CodePudding user response:

It's not an array. Set is an object that holds unique values it has methods like has and add

const set1 = new Set([1, 2, 3, 5, 5, 2, 0]); 
set1.has(2)// returns true
set1.delete(1) // removes the value 1
set1.add(33) // adds the value 33 at the end of the set

you can loop over it in sevral ways on of them using forEach

set1.forEach( value => console.log(value) )

CodePudding user response:

adding elements to a set can be easily achived by add method below is a sample code to delete an element you can use delete method

var set = new Set();  
set.add("one");  
set.add("two");  
set.add("three");  
document.writeln("Size before invoking delete() method: "  set.size "<br>");  
set.delete("three");  
document.writeln("Size after invoking delete() method: " set.size); 

  • Related