skip to Main Content

I have an array of dictionaries and I want to determine if there are any duplicate dictionaries. I tried using the _uniq method from Lodash.js and it looks like it’s finding unique dictionary objects but not determining if they’re equal. I also tried using the Set method which lets me store unique values of any type, whether primitive values or object references.

I know Lodash.js also has a method _.isEqual that determines equality between two unique dictionary objecs so it may be useful.

How can I determine if there is a duplicate dictionary in an array of dictionaries in JavaScript?

// The function should return True because there are two equal dictionaries
arr = [
    {
      "a": 1,
      "b": 2,
    },
    {
      "a": 1,
      "b": 2,
    }
];

// Lodash.js attempt
function hasDuplicate(arr) {
    return _uniq.(arr).length !== arr.length;
}

// Set attempt
function hasDuplicate(arr) {
    const noDuplicates = new Set(arr);
    return arr.length !== noDuplicates.size;
}

2

Answers


  1. Perhaps you could do something more efficient by serializing the objects in a canonical way and comparing these stringified forms, but _.isEqual does yield a fairly straighforward means of detecting dupes:

    function hasDuplicate(arr) {
        for (let i=0; i < arr.length - 1; ++i) {
            // Only need to check for a duplicate against entries later in arr
            for (let j=i+1; j < arr.length; ++j) {
                if (_.isEqual(arr[i], arr[j]))
                    return true;
            }
        }
        return false;
    }
    
    Login or Signup to reply.
  2. Use _.uniqWith() and with _.isEqual() as the predicate:

    function hasDuplicate(arr) {
      return _.uniqWith(arr, _.isEqual).length !== arr.length;
    }
    
    console.log(hasDuplicate([{"a":1,"b":2},{"a":1,"b":2}])); // true
    console.log(hasDuplicate([{"a":1,"b":2},{"a":1,"b":2,"c":3}])); // false
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search