Reputation: 339
I have following code for remove duplicate record. It shows me unique values and removes the last duplicate record. However, what I want is, if two passports are the same, remove both elements from the array.
Example
var array = [{
"PassportNo": "abced",
"Name": "John"
},
{
"PassportNo": "abcederrr",
"Name": "Johnss",
},
{
"PassportNo": "abced",
"Name": "John"
}
];
function removeDuplicates(originalArray, objKey) {
var trimmedArray = [];
var values = [];
var value;
for (var i = 0; i < originalArray.length; i++) {
value = originalArray[i][objKey];
if (values.indexOf(value) === -1) {
trimmedArray.push(originalArray[i]);
values.push(value);
}
}
return trimmedArray;
}
var noDuplicates = removeDuplicates(array, 'PassportNo');
console.log(noDuplicates);
/*
[
{
"PassportNo": "abced",
"Name": "John"
},
{
"PassportNo": "abcederrr",
"Name": "Johnss"
}
]
*/
I want like this (remove both values):
[{
"PassportNo": "abcederrr",
"Name": "Johnss"
}]
Upvotes: 0
Views: 63
Reputation: 12990
You can do this with a simple filter
after storing counts in a separate object (i.e. only choose passports that have count 1).
var array = [{
"PassportNo": "abced",
"Name": "John"
},
{
"PassportNo": "abcederrr",
"Name": "Johnss",
},
{
"PassportNo": "abced",
"Name": "John"
}
];
var passportCounts = array.reduce((map, curr) => {
if (curr.PassportNo in map) map[curr.PassportNo] += 1;
else map[curr.PassportNo] = 1;
return map;
}, {});
console.log(array.filter(p => passportCounts[p.PassportNo] === 1));
Upvotes: 3