skip to Main Content

I’m fairly new and trying to understand maps in javascript.

I have below code.

const topmap = new Map();

const map1 = new Map();
const map2 = new Map();

const set1 = new Set();

map1.set('x','y');
map1.set('a','b');

set1.add(map1);
set1.add(map2);
topmap.set('ID',set1);


console.log(topmap.get('ID').size);
topmap.get('ID').forEach(x => {
  if(x.has('x')){x.delete('x')} )
  
  }
)
console.log(topmap.get('ID').size)

Anyone has any idea why both lines getting their size returning 2 even tho i deleted one map in line 18

2

Answers


  1. Because your topmap.get('ID').size represents your set1 has two map.
    You just delete map’s element rather than map.

    Login or Signup to reply.
  2. On your code above at line if(x.has(‘x’)){x.delete(‘x’)} ), you redundant ) in end of line.

    If you want to remove the entire Map (map1) from the Set (set1), you can use the set1.delete(map1) method. Here’s the corrected code:

    const topmap = new Map();
    
    const map1 = new Map();
    const map2 = new Map();
    
    const set1 = new Set();
    
    map1.set('x', 'y');
    map1.set('a', 'b');
    
    set1.add(map1);
    set1.add(map2);
    topmap.set('ID', set1);
    
    console.log(topmap.get('ID').size);
    
    // Delete the Map from the Set
    topmap.get('ID').forEach(x => {
      if (x.has('x')) {
        set1.delete(x);
      }
    });
    
    console.log(topmap.get('ID').size);  // Should log 1
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search