2017-11-30 2 views
0

Das Array mitWie dedupe ich folgende Array eine Hash-Tabelle

const users = dedup([ 
{ id: 1, email: '[email protected]' }, 
{ id: 2, email: '[email protected]' }, 
{ id: 1, email: '[email protected]' }, 
]); 
/* would ideally like it to return 
Object { 
email: "[email protected]", 
email: "[email protected]", 
id:1 
}, Object { 
email: "[email protected]", 
id:2 
} */ 

der Hash-Tabelle

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); 
}); 
} 

Meine Rückkehr-Anweisung, die nur exakte Duplikate herausfiltert und nicht kommen nicht ähnlich ids mit verschiedene E-Mail-Adressen

console.log(users); 
/* currently returns 
Object { 
email: "[email protected]", 
id:1 
}, Object { 
email: "[email protected]", 
id:2 
}, 
{ id: 1, email: '[email protected]' }, 
]); */ 

Antwort

1
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; 
} 

Ergebnis sollte sein:

{ 
    1: ['[email protected]', '[email protected]' ], 
    2: ['[email protected]'] 
} 

Hope this geholfen.

Verwandte Themen