Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

list of map nested in a set

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading