如何使用哈希 table 对以下数组进行重复数据删除
How do I Dedupe the following array using a hash table
数组
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
} */
哈希 Table
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);
});
}
我的 returns 声明只过滤掉完全重复的并且不加入具有不同电子邮件地址的相似 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']
}
希望对您有所帮助。
数组
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
} */
哈希 Table
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);
});
}
我的 returns 声明只过滤掉完全重复的并且不加入具有不同电子邮件地址的相似 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']
}
希望对您有所帮助。