Creating a hash table using Javascript

A hash table (also called hash map) is a data structure that stores key-value pairs and provides fast lookup, insertion, and deletion operations. In JavaScript, we can implement a hash table using arrays and a hash function to map keys to array indices.

Basic Hash Table Structure

Let's create a hash table class with collision resolution using chaining. We'll use an array of arrays where each index can hold multiple key-value pairs in case of hash collisions.

class HashTable {
    constructor() {
        this.container = [];
        // Initialize container with empty arrays for chaining
        for(let i = 0; i < 11; i++) {
            this.container.push([]);
        }
    }

    // Simple hash function using modulo
    hash(key) {
        return key % 11;
    }

    // Display the hash table contents
    display() {
        this.container.forEach((value, index) => {
            let chain = value
                .map(({ key, value }) => `{ ${key}: ${value} }`)
                .join(" --> ");
            console.log(`${index}: ${chain}`);
        });
    }
}

// Define KVPair class to store key-value pairs
HashTable.prototype.KVPair = class {
    constructor(key, value) {
        this.key = key;
        this.value = value;
    }
}

// Create and display empty hash table
let hashTable = new HashTable();
hashTable.display();
0: 
1: 
2: 
3: 
4: 
5: 
6: 
7: 
8: 
9: 
10: 

Adding Insert Method

Now let's add functionality to insert key-value pairs into our hash table:

class HashTable {
    constructor() {
        this.container = [];
        for(let i = 0; i < 11; i++) {
            this.container.push([]);
        }
    }

    hash(key) {
        return key % 11;
    }

    insert(key, value) {
        let index = this.hash(key);
        let kvPair = new this.KVPair(key, value);
        this.container[index].push(kvPair);
    }

    display() {
        this.container.forEach((value, index) => {
            let chain = value
                .map(({ key, value }) => `{ ${key}: ${value} }`)
                .join(" --> ");
            console.log(`${index}: ${chain}`);
        });
    }
}

HashTable.prototype.KVPair = class {
    constructor(key, value) {
        this.key = key;
        this.value = value;
    }
}

// Test inserting values
let hashTable = new HashTable();
hashTable.insert(10, "Apple");
hashTable.insert(22, "Banana");
hashTable.insert(31, "Orange");
hashTable.insert(4, "Grape");
hashTable.insert(15, "Mango");

hashTable.display();
0: { 22: Banana }
1: { 31: Orange }
2: 
3: 
4: { 4: Grape } --> { 15: Mango }
5: 
6: 
7: 
8: 
9: 
10: { 10: Apple }

Adding Search and Delete Methods

Complete hash table implementation with search and delete functionality:

class HashTable {
    constructor() {
        this.container = [];
        for(let i = 0; i < 11; i++) {
            this.container.push([]);
        }
    }

    hash(key) {
        return key % 11;
    }

    insert(key, value) {
        let index = this.hash(key);
        let kvPair = new this.KVPair(key, value);
        this.container[index].push(kvPair);
    }

    search(key) {
        let index = this.hash(key);
        let bucket = this.container[index];
        for(let pair of bucket) {
            if(pair.key === key) {
                return pair.value;
            }
        }
        return null;
    }

    delete(key) {
        let index = this.hash(key);
        let bucket = this.container[index];
        for(let i = 0; i < bucket.length; i++) {
            if(bucket[i].key === key) {
                bucket.splice(i, 1);
                return true;
            }
        }
        return false;
    }

    display() {
        this.container.forEach((value, index) => {
            let chain = value
                .map(({ key, value }) => `{ ${key}: ${value} }`)
                .join(" --> ");
            console.log(`${index}: ${chain}`);
        });
    }
}

HashTable.prototype.KVPair = class {
    constructor(key, value) {
        this.key = key;
        this.value = value;
    }
}

// Test all operations
let hashTable = new HashTable();
hashTable.insert(10, "Apple");
hashTable.insert(22, "Banana");
hashTable.insert(4, "Grape");

console.log("Search for key 22:", hashTable.search(22));
console.log("Search for key 99:", hashTable.search(99));

hashTable.delete(22);
console.log("After deleting key 22:");
hashTable.display();
Search for key 22: Banana
Search for key 99: null
After deleting key 22:
0: 
1: 
2: 
3: 
4: { 4: Grape }
5: 
6: 
7: 
8: 
9: 
10: { 10: Apple }

Key Features

Our hash table implementation includes several important features:

  • Collision Resolution: Uses chaining to handle hash collisions by storing multiple key-value pairs at the same index
  • Simple Hash Function: Uses modulo operation for quick hash computation
  • Basic Operations: Insert, search, delete, and display functionality
  • Destructuring: Uses modern JavaScript features like destructuring assignment in the display method

Time Complexity

Operation Average Case Worst Case
Insert O(1) O(n)
Search O(1) O(n)
Delete O(1) O(n)

Conclusion

Hash tables provide efficient key-value storage with average O(1) time complexity for basic operations. The chaining approach handles collisions effectively, though a good hash function minimizes collisions for optimal performance.

Updated on: 2026-03-15T23:18:59+05:30

473 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements