我有以下代码用于删除重复记录。它显示了唯一的值,并删除了最后的重复记录。但是,我想要的是,如果两本护照相同,则从数组中删除这两个元素。
示例
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"
}
]
*/
我想要这样(删除两个值):
[{
"PassportNo": "abcederrr",
"Name": "Johnss"
}]
答案 0 :(得分:3)
在将计数存储在单独的对象中后,您可以使用简单的filter
进行此操作(即,仅选择计数为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));