我正在尝试使用哈希表将下面的杂志数组与我的notes数组进行比较。我看看问题并看到它可以通过其他方式完成,但我正在尝试专门学习如何使用哈希表。我想看看杂志中是否有与笔记相同的单词。我的想法是最终得到这样的东西,然后比较它们
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){
}
人们在网上谈论哈希表时有太多的信息和多样性,我变得非常困惑!任何帮助都会很棒!
答案 0 :(得分:1)
如果您想将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));