- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Loop through a hash table using Javascript
Now let us create a forEach function that'll allow us to loop over all key-value pairs and call a callback on those values. For this, we just need to loop over each chain in the container and call the callback on the key and value pairs.
Example
forEach(callback) { // For each chain this.container.forEach(elem => { // For each element in each chain call callback on KV pair elem.forEach(({ key, value }) => callback(key, value)); }); }
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); let sum = 0; // Add all the values together ht.forEach((k, v) => sum += v) console.log(sum);
Output
This will give the output.
228
Advertisements