我正在尝试使用哈希表将下面的杂志数组与笔记数组进行比较。我查看了这个问题,发现可以通过其他方式来完成,但我正在尝试专门学习如何使用哈希表。我想看看杂志中是否有与笔记相同的文字。我的想法是最终得到这样的结果,然后比较它们
magazineHash = {
"cool": 2,
"needs": 1,
"some": 1,
"for": 1,
"work": 1
}
对于注释数组也是如此,然后比较单词的频率(值)
magazine = ["cool", "needs", "some", "for", "work", "cool"];
notes = ["cool", "needs", "for", "cool", "work"]
function reliableNote(magazine, note){
}
人们在网上谈论有关哈希表的信息和种类繁多,我感到非常困惑!任何帮助都会很棒!
最佳答案
如果您想将数组
映射到对象/哈希表
,您可以使用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));
关于javascript - 使用两个哈希表来识别 JavaScript 中的相似之处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50823077/