Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Search Element in an Javascript Hash Table
JavaScript hash tables use a get method to search for elements by their key. The method calculates the hash code and searches through the chain at that index to find the matching key-value pair.
The get() Method Implementation
The search operation involves computing the hash code for the given key and then iterating through the chain at that bucket to find the exact match:
get(key) {
let hashCode = 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) {
return this.container[hashCode][i];
}
}
return undefined;
}
Complete Example
Here's how to test the search functionality with a complete hash table implementation:
// Simple hash function
function hash(key) {
return key % 10;
}
// Hash table class with get method
class HashTable {
constructor() {
this.container = {};
for(let i = 0; i < 10; i++) {
this.container[i] = [];
}
}
put(key, value) {
let hashCode = hash(key);
this.container[hashCode].push({key: key, value: value});
}
get(key) {
let hashCode = hash(key);
for(let i = 0; i < this.container[hashCode].length; i ++) {
if(this.container[hashCode][i].key === key) {
return this.container[hashCode][i];
}
}
return undefined;
}
}
// Testing the search functionality
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.get(21));
console.log(ht.get(55));
console.log(ht.get(32));
{ key: 20, value: 72 }
{ key: 21, value: 6 }
undefined
{ key: 32, value: 34 }
How It Works
The search process follows these steps:
-
Hash Calculation: Calculate the hash code using
hash(key) -
Bucket Access: Access the chain at
this.container[hashCode] - Linear Search: Iterate through the chain to find matching key
-
Return Result: Return the key-value pair if found, otherwise
undefined
Time Complexity
| Case | Time Complexity | Description |
|---|---|---|
| Best Case | O(1) | Element is first in chain |
| Average Case | O(1) | Good hash distribution |
| Worst Case | O(n) | All elements in same chain |
Conclusion
The hash table search operation provides efficient key-based lookups by combining hash computation with chain traversal. It returns the complete key-value pair object or undefined if the key doesn't exist.
Advertisements
