Guest User

Untitled

a guest
May 24th, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.08 KB | None | 0 0
  1. var groceryList = [
  2. {
  3. item: "Bananas",
  4. count: 4
  5. },
  6. {
  7. item: "Bananas",
  8. count: 3
  9. },
  10. {
  11. item: "Brussel Sprouts",
  12. count: 2
  13. },
  14. {
  15. item: "Bacon",
  16. count: 100
  17. },
  18. {
  19. item: "Beans",
  20. count: 19
  21. },
  22. {
  23. item: "Beans",
  24. count: 5
  25. }
  26. ]
  27.  
  28. const seen = {}
  29. const newList = []
  30. var removeDups = []
  31. const list = groceryList.map(function(item) {
  32. // if we haven't this item before (via check on item name) push it into seen object
  33. // also push it to newList array
  34. if (!seen[item.item]) {
  35. seen[item.item] = item
  36. newList.push(item)
  37. }
  38. // if we have seen the item during iteration...
  39. else if (seen[item.item]) {
  40. // remove it from the newList array
  41. removeDups = newList.filter(function(listItem) {
  42. if (listItem.item == item.item) {
  43. console.log('matched');
  44. } else {
  45. return true
  46. }
  47. })
  48.  
  49. // and push in the item with the higher count
  50. if (seen[item.item].count > item.count) {
  51. removeDups.push(seen[item.item])
  52. } else {
  53. removeDups.push(item)
  54. }
  55. }
  56. })
  57.  
  58. console.log(removeDups);
Add Comment
Please, Sign In to add comment