Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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) {
- // if we haven't this item before (via check on item name) push it into seen object
- // also push it to newList array
- if (!seen[item.item]) {
- seen[item.item] = item
- newList.push(item)
- }
- // if we have seen the item during iteration...
- else if (seen[item.item]) {
- // remove it from the newList array
- removeDups = newList.filter(function(listItem) {
- if (listItem.item == item.item) {
- console.log('matched');
- } else {
- return true
- }
- })
- // and push in the item with the higher count
- if (seen[item.item].count > item.count) {
- removeDups.push(seen[item.item])
- } else {
- removeDups.push(item)
- }
- }
- })
- console.log(removeDups);
Add Comment
Please, Sign In to add comment