How to find duplicates in key value pairs array sails.js
-
20-12-2019 - |
Question
I have an array as below.
[emails] => Array (
[0] => Array (
[a] => a@a.com
[is_verified_a] => 1
)
[1] => Array (
[b] => a@a.com
[is_verified_b] => 1
)
),
I need to find duplicates in this array , but keys are different ie a and b have the same email 'a@a.com'.
ie , Have to check for duplicates in this array and need only the value 'a@a.com' in a separate variable. Is there any way to find out using _.uniq or any other underscore functions?
Please help.Thanks a lot.
Solution
What you want to do is not clear. However since you're using JavaScript your array should look like:
var emails = [
{
email: "a@a.com",
verified: true,
key: "a"
},
{
email: "a@a.com",
verified: true,
key: "b"
}
];
It makes no sense to encode keys in your objects separately (especially not in property names).
To remove duplicates from an array we can create a generic removeDuplicatesBy
function:
function removeDuplicatesBy(comparator, array) {
var length = array.length;
var unique = [];
for (var i = 0; i < length; i++) {
var element = array[i];
var isUnique = true;
for (var j = 0; j < i; j++) {
if (comparator(element, array[j])) {
isUnique = false;
break;
}
}
if (isUnique) unique.push(element);
}
return unique;
}
Now we can remove duplicates in the emails
array as follows:
var uniqueEmails = removeDuplicatesBy(function (a, b) {
return a.email === b.email && a.verified === b.verified;
}, emails);
If you need to maintain keys in your objects then you're probably doing something wrong. You should consider restructuring your code.