HashMap in JavaScript
HashMap in JavaScript
Section titled “HashMap in JavaScript”In JS, a HashMap is implemented using:
Map(preferred modern way)- plain object
{}(older way)
Using Map (Recommended)
Section titled “Using Map (Recommended)”Create Map
Section titled “Create Map”const map = new Map();Basic Operations
Section titled “Basic Operations”set() insert/update
Section titled “set() insert/update”map.set("name", "John");map.set("age", 25);Time: O(1)
get() retrieve
Section titled “get() retrieve”map.get("name"); // "John"Time: O(1)
has() check existence
Section titled “has() check existence”map.has("age"); // trueTime: O(1)
delete()
Section titled “delete()”map.delete("age");Time: O(1)
map.size;Example Walkthrough
Section titled “Example Walkthrough”const freq = new Map();
const arr = [1, 2, 2, 3];
for (let num of arr) { freq.set(num, (freq.get(num) || 0) + 1);}
console.log(freq);// Map {1 => 1, 2 => 2, 3 => 1}Very common interview pattern