October 21, 2024
Chicago 12, Melborne City, USA
javascript

How can you check if a javascript map has a duplicate key


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



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video