Reputation: 63
I am trying to use hash tables to compare my magazine array below with my notes array. I look at the problem and see that it could be done in other ways but I am trying to specifically learn how to use hash tables. I want to see if magazine has the same words within it as notes. My idea is to end up with something like this and then compare them
magazineHash = {
"cool": 2,
"needs": 1,
"some": 1,
"for": 1,
"work": 1
}
and the same for notes array and then to compare the frequencies (values) of the words
magazine = ["cool", "needs", "some", "for", "work", "cool"];
notes = ["cool", "needs", "for", "cool", "work"]
function reliableNote(magazine, note){
}
There is so much info and variety in what people talk about regarding hash tables online, I am getting very confused! Any help would be awesome!
Upvotes: 0
Views: 103
Reputation: 3115
If you want to map an array
to an object/hash table
you could use the reduce
function:
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));
Upvotes: 1