Search code examples
javascriptobjectkeyvaluepair

Remove key/value pairs with the same value (i.e. duplicates) in an object in Javascript


I'm currently learning JS and I need a way to return an object that is similar to the given object but removing key/value pairs that have the same value (i.e. duplicates).

So if I had a given object { a: 1, b: 2, c: 3, d: 1 }:

it should return:

{b: 2, c: 3 }

Similarly, if all key-value pairs in an object had different values, the returned object would simply be the same as the given object.

I think I am close to solving it but I can't figure out what's wrong with my code. Any help would be much appreciated!

const noDuplicateValues = (obj) => {
  let result = {};
  let keys = Object.keys(obj);
  let duplicate;

  for(let i = 0; i < keys.length; i++) {
    for(let j = i +1; j < keys.length; j++) {
      duplicate = false;
      if(obj[keys[i]] === obj[keys[j]]) {
        duplicate = true;
      }
    }
    if(!duplicate) {
      result[keys[i]] = obj[keys[i]];
    } 
  }
  return result;
}

Solution

  • To speed things up, your inner loop can exit as soon as it finds a duplicate. But the flaw which is preventing it from working correctly is that while it finds that a is a duplicate of d and correctly omits a, it doesn't omit d because when it checks d, which is the last element in the array, there are no subsequent elements to compare against, so it doesn't consider d to be a duplicate.

    The fix is to make the inner loop check every element (not just the ones after the one being checked by the outer loop), of course being careful not to check an element against itself:

    const noDuplicateValues = (obj) => {
        let result = {};
        let keys = Object.keys(obj);
        let duplicate;
    
        for (let i = 0; i < keys.length; i++) {
            duplicate = false;
            for (let j = 0; j < keys.length; j++) {
                if (
                    i !== j // Don't compare an element with itself
                    &&
                    obj[keys[i]] === obj[keys[j]]
                ) {
                    duplicate = true;
                    break; // Found a dupe so we can stop checking this one for dupes
                }
            }
            if (!duplicate) {
                result[keys[i]] = obj[keys[i]];
            }
        }
        return result;
    }
    
    var x = noDuplicateValues({ a: 1, b: 2, c: 3, d: 1 });
    console.log(x); // Object { b: 2, c: 3 }