I’m working with a Map in JavaScript and need to check that it doesn’t contain duplicate keys. The map I’m working with is below.
const colors = new Map([
[1, 'blue'],
[2, 'orange'],
[1, 'pink'], // This duplicate key should trigger an error
[3, 'yellow'],
]);
In this situation because the number 1 is used two times as a key that should throw an error.
I cannot modify the colors variable directly. Instead, I need to make a function that checks for duplicate keys in the Map and throw an error if a duplicate is found.
This is what I currently have. The problem is that when you use a duplicate key in the map it overrides the previous key and value so it’s as if a duplicate key is never in the map.
const colors = new Map([
[1, 'blue'],
[2, 'orange'],
[1, 'pink'], // This duplicate key should trigger an error
[3, 'yellow'],
]);
const iterator = colors.keys();
console.log(iterator.next().value);
// output: 1
console.log(iterator.next().value);
// output: 2
console.log(iterator.next().value);
// output: 3
4
Answers
I have addd checkForDuplicateKeys
the Set (seenKeys) keep track of keys.
if a duplicate key is found it throws an error.
My suggestion:
In case of duplicate key, the function will throw an error displaying that key (in the example above: 1).
I’d go with comparison of Array length and Set size, since creating a Set with duplicate values will reduce the existing ones. The magic happens in
hasDuplicateEntries