使用两个哈希表来识别 JavaScript 中的相似之处



我正在尝试使用哈希表将下面的杂志数组与我的笔记数组进行比较。 我看了这个问题,发现可以用其他方式完成,但我正在尝试专门学习如何使用哈希表。 我想看看杂志中是否有与笔记相同的单词。我的想法是最终得到这样的东西,然后比较它们

magazineHash = {
"cool": 2,
"needs": 1,
"some": 1,
"for": 1,
"work": 1
}

和 notes 数组相同,然后比较单词的频率(值(

magazine = ["cool", "needs", "some", "for", "work", "cool"];
notes = ["cool", "needs", "for", "cool", "work"]
function reliableNote(magazine, note){
}

人们谈论的关于在线哈希表的信息和种类太多,我感到非常困惑! 任何帮助都会很棒!

如果要将array映射到object/hash table可以使用reduce函数:

const magazine = ["cool", "needs", "some", "for", "work", "cool"];
const notes = ["cool", "needs", "for", "cool", "work"]
function mapToHash(arr) {
return arr.reduce((hash, entry) => ({ ...hash,
[entry]: hash[entry] ? hash[entry] + 1 : 1
}), {})
}
console.log(mapToHash(magazine));
console.log(mapToHash(notes));

最新更新