Remove elements from Javascript Hash Table



To remove elements, we simply need to find them and remove them using a simple splice function call that removes elements in place from an array.

Let us look at the implementation of the same − 

Example

remove(key) {
   let hashCode = this.hash(key);

   for (let i = 0; i < this.container[hashCode].length; i++) {
      // Find the element in the chain
      if (this.container[hashCode][i].key === key) {
         this.container[hashCode].splice(i, 1);
         return true
      }
   }
   return false;
}

You can test this using − 

Example

let ht = new HashTable();

ht.put(10, 94); ht.put(20, 72);
ht.put(30, 1);
ht.put(21, 6);
ht.put(15, 21);
ht.put(32, 34);

console.log(ht.get(20));
console.log(ht.remove(20));
console.log(ht.get(20));
console.log(ht.remove(20));

Output

This will give the output −

{ key: 20, value: 72 }
true
undefined
false

This returned true the first time because it was found and deleted successfully. The next time, since it wasn't present, the remove function returned false.

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know


Advertisements