JavaScript Associative Array and Hash Table
- Create JavaScript Associative Array Using Objects
-
Create JavaScript Associative Array Using
Map()
Function - Use JavaScript Object to Implement Hash Table
We will learn about implementing JavaScript associative array and hash table using objects and Map()
.
Though JavaScript does not have associative arrays/hash tables except objects. But there are other ways around doing it.
Before diving into the detailed implementation, it is requisite to know the difference between associative array, map, dictionary, and hash table. Although all of these are used to hold key-value pair data, there is still a difference.
- An associative array is a data structure concept that contains the data in (key, value) pairs. It is also known as abstract data type, just like maps and dictionaries. Here indices are strings, not integers. There are different ways to implement an associative array; the hash table is one of them.
- The dictionary also holds data in (key, value) pair same as the associative array. But, its indices are integers.
- The map also has data in key-value pairs. It remembers the key’s original insertion order.
- A hash table is all about arranging data in memory using the hash method. It is one of the ways to simulate an associative array.
Create JavaScript Associative Array Using Objects
// first way to create associative array
const person = [];
person['firstname'] = 'Mehvish';
person['lastname'] = 'Ashiq';
person['age'] = 30;
person['city'] = 'Multan';
person['email'] = 'delfstack@example.com';
// second way to create associative array
const person = {
firstname: 'Mehvish',
lastname: 'Ashiq',
age: 30,
city: 'Multan',
email: 'delfstack@example.com'
};
We created a JavaScript object that functions as an associative array in the code above. The firstname
, lastname
, age
, city
, and email
are keys (indices). The values are Mehvish
, Ashiq
, 30
, Multan
, delfstack@example.com
.
Just assume that we want to add a new key-value pair as phone:12334567
. For that, we can use Object.assign()
function. It copies the second object to the end of the first object.
// Here the second object is {phone:12334567}
// Here the first object is person
Object.assign(person, {phone: 12334567});
We can access each key’s value by targeting the keys (indices). Remember, the indices are strings, not numbers. So, you can’t access like person[0]
here (you can use person[0]
if you are using dictionaries).
// to print in the browser
document.write(person.firstname); // OUTPUT: Mehvish
document.write(person['firstname']); // OUTPUT: Mehvish
document.write(person[0]); // OUTPUT: undefined
// to print on console
console.log(person.firstname); // OUTPUT: Mehvish
console.log(person[0]); // OUTPUT: undefined
We can print the complete associative array using the for
loop.
// print complete associative array using for look
for (var key in person) {
var value = person[key];
document.write(value);
document.write(' ');
}
Output:
"[firstname: Mehvish]"
"[lastname: Ashiq]"
"[age: 30]"
"[city: Multan]"
"[email: delfstack@example.com]"
"[phone: 12334567]"
The more optimized way to print the whole associative array is the Object.entries()
method that takes one parameter of object data type. You can read this for more Object’s functions.
// print complete associative array using for look
let completeAssociateArray = Object.entries(person);
console.log(completeAssociateArray);
Output:
[["firstname", "Mehvish"], ["lastname", "Ashiq"], ["age", 30], ["city", "Multan"], ["email", "delfstack@example.com"], ["phone", 12334567]]
Create JavaScript Associative Array Using Map()
Function
// first way to create associative array using Map function
const person = new Map();
person.set('firstname', 'Mehvish');
person.set('lastname', 'Ashiq');
person.set('age', 30);
person.set('city', 'Multan');
person.set('email', 'delfstack@example.com');
// second way to create associative array using Map function
const person = new Map([
['firstname', 'Mehvish'], ['lastname', 'Ashiq'], ['age', 30],
['city', 'Multan'], ['email', 'delfstack@example.com']
]);
Using the get(key)
method, we can get a particular value.
person.get('city'); // output is "Multan"
Display whole associative array key-value pairs.
for (const [key, value] of person.entries()) {
console.log(key + ' = ' + value)
}
Output:
"firstname = Mehvish"
"lastname = Ashiq"
"age = 30"
"city = Multan"
"email = delfstack@example.com"
Print only keys using the keys()
function.
for (const key of person.keys()) {
console.log(key)
}
Output:
"firstname"
"lastname"
"age"
"city"
"email"
Get values only using values()
function.
for (const value of person.values()) {
console.log(value)
}
Output:
"Mehvish"
"Ashiq"
30
"Multan"
"delfstack@example.com"
We can use the delete(key)
to remove an element; it returns true
if successfully deleted. The has(key)
returns true
if an element is associated with the given key, while clear()
removes all key-value pairs.
For a detailed understanding, you can visit this page. If you are looking for a hash table implementation, you can use Map()
function, but we are using a JavaScript object to implement the hash table.
Use JavaScript Object to Implement Hash Table
var ht = new HashTable({firstname: 'Mehvish', lastname: 'Ashiq', age: 30});
function HashTable(person) {
this.size = 0;
this.item = {};
for (var p in person) {
if (person.hasOwnProperty(p)) {
this.item[p] = person[p];
this.size++;
}
}
this.set =
function(key, value) {
var previousItem = undefined;
if (this.has(key)) {
previousItem = this.item[key];
} else {
this.size++;
}
this.item[key] = value;
return previousItem;
}
this.get =
function(key) {
return this.has(key) ? this.item[key] : undefined;
}
this.has = function(key) {
return this.item.hasOwnProperty(key);
}
}
Let’s test it by using the following code.
console.log(ht.size);
console.log(ht.get('firstname'));
It gives the following results.
3
"Mehvish"
The hasOwnProperty
method is used to check whether a key belongs to the item
object. In other words, it returns true
if the given property directly belongs to the item
object.
The set
, get
, and has
is just a mimicked form of Object’s functions.