数组
const users = dedup([
{ id: 1, email: 'foo@example.com' },
{ id: 2, email: 'sho@example.com' },
{ id: 1, email: 'bin@example.com' },
]);
/* would ideally like it to return
Object {
email: "foo@example.com",
email: "bin@example.com",
id:1
}, Object {
email: "sho@example.com",
id:2
} */
哈希表
function dedup(arr) {
var hashTable = {};
return arr.filter(function (el) {
var key = JSON.stringify(el);
var match = Boolean(hashTable[key]);
return (match ? false : hashTable[key] = true);
});
}
我的返回声明仅过滤掉完全相同的重复项,并且不会将相似的 ID 与不同的电子邮件地址连接起来
console.log(users);
/* currently returns
Object {
email: "foo@example.com",
id:1
}, Object {
email: "sho@example.com",
id:2
},
{ id: 1, email: 'bin@example.com' },
]); */
最佳答案
function dedup(arr) {
var hashTable = {};
arr.forEach(function(el) {
if (!hashTable.hasOwnProperty(el.id)) {
hashTable[el.id] = [];
}
hashTable[el.id].push(el.email);
});
return hashTable;
}
结果应该是:
{
1: ['bin@example.com', 'foo@example.com' ],
2: ['sho@example.com']
}
希望这有帮助。
关于javascript - 如何使用哈希表对以下数组进行重复数据删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47566729/