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
Dictionary Data Structure in Javascript
In computer science, an associative array, map, symbol table, or dictionary is an abstract data type composed of a collection of (key, value) pairs, such that each possible key appears at most once in the collection. Note that a dictionary is also known as a map.
The dictionary problem is a classic computer science problem: the task of designing a data structure that maintains a set of data during 'search', 'delete', and 'insert' operations. There are many different types of implementations of dictionaries.
- Hash Table implementation
- Tree-Based Implementation (Self-balancing and Unbalanced trees)
- List based implementation
When to use a Dictionary
Dictionaries are not a silver bullet and should not be used at every chance you get. They are useful in many scenarios, but you need to keep the following points in mind before deciding to use a dictionary to solve a problem.
- Inserts are generally slow, reads are faster than trees.
- Use these for fast lookups, for example, to cache data, index databases, symbol tables, etc.
- When the order of elements doesn't matter.
- When all element keys are unique.
Dictionary Implementation in JavaScript
JavaScript provides several built-in options for dictionary-like behavior. The most common approaches are using Objects or the Map class.
Using JavaScript Objects
// Create a dictionary using object
let dictionary = {};
// Add key-value pairs
dictionary["name"] = "John";
dictionary["age"] = 30;
dictionary["city"] = "New York";
console.log(dictionary);
console.log("Name:", dictionary["name"]);
console.log("Age:", dictionary.age); // Dot notation also works
{ name: 'John', age: 30, city: 'New York' }
Name: John
Age: 30
Using JavaScript Map
// Create a dictionary using Map
let dictionary = new Map();
// Add key-value pairs
dictionary.set("name", "Alice");
dictionary.set("age", 25);
dictionary.set("city", "Boston");
console.log("Name:", dictionary.get("name"));
console.log("Has age key:", dictionary.has("age"));
console.log("Size:", dictionary.size);
Name: Alice Has age key: true Size: 3
Custom Dictionary Class Implementation
Let's implement a custom Dictionary class with all the essential methods:
class Dictionary {
constructor() {
this.data = {};
}
// Put key-value pair
put(key, value) {
this.data[key] = value;
}
// Get value by key
get(key) {
return this.data[key];
}
// Check if key exists
hasKey(key) {
return key in this.data;
}
// Delete a key
delete(key) {
if (this.hasKey(key)) {
delete this.data[key];
return true;
}
return false;
}
// Clear all entries
clear() {
this.data = {};
}
// Get all keys
keys() {
return Object.keys(this.data);
}
// Get all values
values() {
return Object.values(this.data);
}
// Get size
size() {
return Object.keys(this.data).length;
}
}
// Example usage
let dict = new Dictionary();
dict.put("apple", 5);
dict.put("banana", 3);
dict.put("orange", 8);
console.log("Apple count:", dict.get("apple"));
console.log("Has banana:", dict.hasKey("banana"));
console.log("All keys:", dict.keys());
console.log("All values:", dict.values());
console.log("Size:", dict.size());
dict.delete("banana");
console.log("After deleting banana:", dict.keys());
Apple count: 5 Has banana: true All keys: [ 'apple', 'banana', 'orange' ] All values: [ 5, 3, 8 ] Size: 3 After deleting banana: [ 'apple', 'orange' ]
Methods Overview
Our dictionary implementation includes the following essential methods:
- get(): Gets the element with the input key
- put(): Puts the key-value pair in the dictionary
- hasKey(): Checks if the key is present in the dictionary
- delete(): Removes the given key from the dictionary
- clear(): Removes all key-value pairs from the dictionary
- keys(): Returns all keys as an array
- values(): Returns all values as an array
Comparison: Object vs Map vs Custom Dictionary
| Feature | Object | Map | Custom Dictionary |
|---|---|---|---|
| Key Types | String/Symbol only | Any type | String/Symbol only |
| Size Property | Manual calculation | Built-in size | Custom method |
| Iteration | for...in loop | for...of loop | Custom methods |
| Performance | Fast for small data | Optimized for frequent additions/deletions | Depends on implementation |
Conclusion
JavaScript offers multiple ways to implement dictionaries, from simple objects to the Map class or custom implementations. Choose based on your specific needs: objects for simple string keys, Map for complex key types, or custom classes for specialized behavior.
