1

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 }
1
  • 1
    The code you posted does not create any 4 keys since there are no 4 values in your nums array. Please provide a minimal reproducible example. Commented Sep 10, 2022 at 4:30

2 Answers 2

1

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];
Sign up to request clarification or add additional context in comments.

Comments

0
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.