Here is a challenge I encountered with a grocery list that required filtering out duplicates and only keeping the duplicate with the higher count, while also retaining non-duplicate items. I managed to achieve this through trial and error programming, but I am eager to discover a more efficient solution. The code below describes the steps I took and my thinking process. If anyone knows of a better approach to solving this problem, I am open to learning.
var groceryList = [
{
item: "Bananas",
count: 4
},
{
item: "Bananas",
count: 3
},
{
item: "Brussel Sprouts",
count: 2
},
{
item: "Bacon",
count: 100
},
{
item: "Beans",
count: 19
},
{
item: "Beans",
count: 5
}
]
const seen = {}
const newList = []
var removeDups = []
const list = groceryList.map(function(item) {
// Add new items to seen object and newList array
if (!seen[item.item]) {
seen[item.item] = item
newList.push(item)
}
// Handle duplicates
else if (seen[item.item]) {
// Filter out duplicates from newList
removeDups = newList.filter(function(listItem) {
if (listItem.item == item.item) {
console.log('matched');
} else {
return true
}
})
// Keep only the item with higher count
if (seen[item.item].count > item.count) {
removeDups.push(seen[item.item])
} else {
removeDups.push(item)
}
}
})
console.log(removeDups);