So I'm trying to count the number of times an object repeats in an array of objects.
Here is the what the array looks like:
[{ Title: 'Einstein', Author: 'Walter Isaacson' },
{ Title: 'The Elegant Universe', Author: 'Brian Greene' },
{ Title: 'The Elegant Universe', Author: 'Brian Greene' },
{ Title: 'Empire', Author: 'Niall Ferguson' },
{
Title: 'The End of History and the Last Man',
Author: 'Francis Fukuyama'
},
{ Title: 'The End of the World', Author: 'John Leslie' },
{ Title: 'Enduring Love', Author: 'Ian McEwan' }]
Here is the map attempting to store the count of each object occurrence :
const mp = new Map()
for (obj of collection){
if(mp.has(obj)){
mp.set(obj, mp.get(obj) 1)
} // saying that mp doesnt have obj? i think it's hitting the else instead of the if?
else {
mp.set(obj, 1)
}
}
However, the map returns 1 for each book when know there are duplicates. I'm working with a pretty large txt file. I can see the duplicates before turning them into a map. Any help or insight would be appreciated.
CodePudding user response:
Object in Javascript is a reference type, all off them will show up as unique because when you compare, it does not compare by the value but by the reference. And each of those objects point to a different location in memory.
CodePudding user response:
You can try this :
const sum = arr => arr.reduce((partialSum, a) => partialSum a, 0);
collection.map(obj => { return { 'obj': obj, 'count': sum(col.map(obj2 => {
if(JSON.stringify(obj) == JSON.stringify(obj2)) return 1;
return 0;
})) }} );