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
Loop through a hash table using Javascript
Hash tables (also called hash maps) store key-value pairs and provide efficient lookup. To iterate through all entries, we need to traverse each chain in the underlying storage container since hash tables typically use chaining to handle collisions.
Creating a forEach Method
The forEach method loops over all key-value pairs in the hash table and executes a callback function for each pair. We iterate through each chain in the container and process every key-value pair.
forEach(callback) {
// For each chain in the hash table
this.container.forEach(elem => {
// For each element in each chain call callback on KV pair
elem.forEach(({ key, value }) => callback(key, value));
});
}
Complete Example
Here's how to use the forEach method to iterate through a hash table and perform operations on the stored values:
// Assuming we have a HashTable class implementation
let ht = new HashTable();
// Adding key-value pairs to the hash table
ht.put(10, 94);
ht.put(20, 72);
ht.put(30, 1);
ht.put(21, 6);
ht.put(15, 21);
ht.put(32, 34);
let sum = 0;
// Add all the values together using forEach
ht.forEach((k, v) => {
console.log(`Key: ${k}, Value: ${v}`);
sum += v;
});
console.log("Total sum:", sum);
Key: 10, Value: 94 Key: 20, Value: 72 Key: 30, Value: 1 Key: 21, Value: 6 Key: 15, Value: 21 Key: 32, Value: 34 Total sum: 228
Alternative Iteration Methods
Besides forEach, you can also implement other iteration methods for different use cases:
// Get all keys
keys() {
let keys = [];
this.forEach((key, value) => keys.push(key));
return keys;
}
// Get all values
values() {
let values = [];
this.forEach((key, value) => values.push(value));
return values;
}
// Convert to array of [key, value] pairs
entries() {
let entries = [];
this.forEach((key, value) => entries.push([key, value]));
return entries;
}
Conclusion
The forEach method provides a clean way to iterate through hash table entries by traversing each chain and processing key-value pairs. This approach handles collision resolution and ensures all stored data is accessible during iteration.
