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
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:Use
_.uniqWith()
and with_.isEqual()
as the predicate: