javascript - 如何使用哈希表对以下数组进行重复数据删除

标签 javascript arrays duplicates hashtable

数组

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/

相关文章:

javascript - 在不到 O(n) 的时间内找到(排序的)数组中的重复元素?

Javascript $(function() 不适用于 WordPress

Java - 查找数组的平均值,同时排除特定值。

javascript - 对象 Javascript 的数组访问

python - matplotlib.scatter 颜色参数不接受 numpy 数组

javascript - 从数组中删除重复元素(利用对象) - Javascript

python - 如何在 Pandas DataFrame 中查找某些列中具有相同/相反符号的相同值的匹配行?

MySQL REPLACE 和 DUPLICATE KEY 未给出列值之和

java - 使用 SAX 解析器解析可能重复的嵌套 XML 标签。 java

javascript - CoffeeScript 类中是否可以有同名的静态函数和成员函数?