skip to Main Content

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


  1. I have addd checkForDuplicateKeys
    the Set (seenKeys) keep track of keys.
    if a duplicate key is found it throws an error.

    function checkForDuplicateKeys(entries) {
        const seenKeys = new Set(); 
        
        for (const [key, value] of entries) {
            if (seenKeys.has(key)) {
                throw new Error(`duplicate key found: ${key}`);
            }
            seenKeys.add(key); // add the key to the set
        }
    }
    
    const colorEntries = [
        [1, 'blue'],
        [2, 'orange'],
        [1, 'pink'], // This duplicate key should trigger an error
        [3, 'yellow'],
    ];
    
    try {
        checkForDuplicateKeys(colorEntries); 
        //if no error
        const colors = new Map(colorEntries); 
        console.log(colors);
    } catch (error) {
        console.error(error.message); 
    }
    Login or Signup to reply.
  2. My suggestion:

    const entries = [
      [1, 'blue'],
      [2, 'orange'],
      [1, 'pink'],
      [3, 'yellow'],
    ];
    
    function checkDuplicateKeys(entries) {
      const keySet = new Set();
      const duplicates = [];
    
      entries.forEach(([key, value], index) => {
        if (keySet.has(key)) {
          duplicates.push({
            key,
            index
          });
        } else {
          keySet.add(key);
        }
      });
    
      if (duplicates.length > 0) {
        const keys = duplicates.map(d => d.key).join(', ');
        const errorMessage = `Duplicate key(s) found: ${keys}.`;
    
        throw new Error(errorMessage);
      }
    }
    
    try {
      checkDuplicateKeys(entries);
      const colors = new Map(entries);
      console.log('Map created successfully:', colors);
    } catch (error) {
      console.error(error.message);
    }

    In case of duplicate key, the function will throw an error displaying that key (in the example above: 1).

    Login or Signup to reply.
  3. const values = [
        [1, "blue"],
        [2, "orange"],
        [1, "pink"], // This duplicate key should trigger an error
        [3, "yellow"],
    ];
    const colors = new Map(
        values.map((value) => {
            if (values.filter((element) => value[0] == element[0]).length == 1) {
                return value;
            } else {
                throw new Error(` key ${value[0]} is duplicate `);
            }
        })
    );
    
    Login or Signup to reply.
  4. 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

    const colorEntriesWithDuplicate = [
      [1, 'yellow'],
      [2, 'blue'],
      [1, 'green'],
      [3, 'red']
    ];
    
    const colorEntriesWithoutDuplicate = [
      [1, 'yellow'],
      [2, 'blue'],
      [3, 'red']
    ];
    
    const hasDuplicateEntries = (entries) => {
      return entries.length !== new Set(entries.map(([key, val]) => key)).size;
    }
    
    
    console.log(hasDuplicateEntries(colorEntriesWithDuplicate));
    
    console.log(hasDuplicateEntries(colorEntriesWithoutDuplicate));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search