Home > other >  Unable to delete map entries using map.delete() function
Unable to delete map entries using map.delete() function

Time:09-10

I'm trying to delete the entry with key '1' in the map. Can anyone tell me why is map.delete(1) returning false and the entry is not being deleted.

let nums = [1,1,1,2,2,3]
let map = new Map();
    for (let num of nums) {
        if (num in map) {
            map[num]  ;
        } else {
            map[num] = 1;
        }
    }
    console.log(map) // Map(0) { '1': 3, '2': 2, '3': 1, '4': 3 }
    console.log(map.delete(1)); // false
    console.log(map) // Map(0) { '1': 3, '2': 2, '3': 1, '4': 3 }

CodePudding user response:

let nums = [1,1,1,2,2,3, 4]
let map = new Map();
for (let num of nums) {
    if (num in map) {
        map.set(num, map.get(num)  );
    } else {
        map.set(num, 1)
    }
}
console.log(map)
console.log(map.delete(1))
console.log(map)

CodePudding user response:

You need to use map.get() and map.set() instead of bracket syntax. Assigning properties to a map object doesn't actually use the Map, and is why map.delete() does nothing.

Either use a Map:

const map = new Map();
for (let num of nums) {
    if (map.has(num)) {
        map.set(num, map.get(num) 1);
    } else {
        map.set(num, 1);
    }
}
map.delete(1);

Or (ab)use an object as a collection:

const map = Object.create(null);
for (let num of nums) {
    if (num in map) {
        map[num]  ;
    } else {
        map[num] = 1;
    }
}
delete map[1];
  • Related